I suggest you use the built in error handling in laravel: https://laravel.com/docs/9.x/errors#main-content
Mar 10, 2022
7
Level 4
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?
Please or to participate in this conversation.