-1

I want to handle 500 Internal Server Error as a JSON response in my postman, please help me.

I have this kind of code in Exception/Handler.php and I don't have any idea how to handle a 500 Internal Server Error that returns a JSON response in POSTMAN.

    $this->renderable(function (HttpException $e, $request) {
        if($request->is('api/*')){
            return response()->json(['message'=> $e->getMessage(),'code' => $e->getStatusCode()]);
    }});

2 Answers2

0

It is a example in Laravel Docs:

public function register()
{
    $this->renderable(function (InvalidOrderException $e, $request) {
        return response()->view('errors.invalid-order', [], 500);
});
}

https://laravel.com/docs/8.x/errors

giuarnhold
  • 31
  • 3
  • For API, you should always use an error handler also. – Rajeev Singh Sep 21 '21 at 05:35
  • @RajeevSingh can you write answer about how to handle validation error response & 500 internal server error for API requests globally using error handler in Laravel 9+? – Harsh Patel Mar 02 '23 at 09:10
  • @HarshPatel there is many methods for manage exception or error controlling in laravel but most important - you should use always try catch for exception handler. For other method see few example - https://laraveldaily.com/post/how-to-catch-handle-create-laravel-exceptions – Rajeev Singh Mar 04 '23 at 09:28
  • yes I know about this but can you tell me about how can we set global exception handler for some errors like 500 etc. so if we forgotted to handled perticular function than global error handler will return Json response about internal server error to the API Requests. I know about laravel 8 but for laravel 9 I can't found any solution – Harsh Patel Mar 04 '23 at 09:47
0

you can easily use try/catch in your controller ,

for example for this code something look like this, and in response return whatever status you want instead Server error series code.

use Illuminate\Http\Response;
try {
  // code 
  // 
    } catch (\Exception $e) {
        return response()->json(['message' => $e->getMessage()], Response::HTTP_NOT_FOUND);
    }
Masoud
  • 1,099
  • 1
  • 10
  • 22