Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

panthro's avatar

Very simple API error response

I'm trying to create a basic API and I was wondering how to do a generic response inase of error, for example...

 try {
            User::create($request->validated());
        } catch (Exception $e) {
            $message = 'User not created.';
            $code = 500;
        }

        return response([
            'message' => $message ?? 'User successfully created.',
        ], $code ?? 201);

With the above I manually write a generic code and message in the catch block. My question is, should this be handled differently? Should I get the message and error code from the exception?

0 likes
7 replies
anilkumarthakur60's avatar
  public function userCreate(Request $request)
    {

        $data = $this->validate($request, [
            //validation rule
        ]);

        $user = User::create($data);

        return response()->json(['data' => $user, 'message' => 'user created successfully', 'status_code' => 201]);
    }
anilkumarthakur60's avatar

if you think the above code is also going to return 201 then you should learning https://laracasts.com/series/laravel-8-from-scratch

here is another code for you


 $data = $this->validate($request, [
            //validation rule
        ]);

  try {
            DB::beginTransaction();
           $user = User::create($data);
            DB::commit();
        } catch (QueryException $exception) {
            DB::rollBack();
            throw new InvalidArgumentException($exception->getMessage());
        }
   return response()->json(['data' => $user, 'message' => 'user created successfully', 'status_code' => 201]);
tykus's avatar

@panthro what exception(s) are you anticipating from creating the User instance?

Please or to participate in this conversation.