How to Send Laravel Error Responses as JSON

How can I make Laravel return a custom error for a JSON REST API

go to your app/start/global.php.

This will convert all errors for 401 and 404 to a custom json error instead of the Whoops stacktrace. Add this:

App::error(function(Exception $exception, $code)
{
Log::error($exception);

$message = $exception->getMessage();

// switch statements provided in case you need to add
// additional logic for specific error code.
switch ($code) {
case 401:
return Response::json(array(
'code' => 401,
'message' => $message
), 401);
case 404:
$message = (!$message ? $message = 'the requested resource was not found' : $message);
return Response::json(array(
'code' => 404,
'message' => $message
), 404);
}

});

This is one of many options to handle this errors.


Making an API it is best to create your own helper like Responser::error(400, 'damn') that extends the Response class.

Somewhat like:

public static function error($code = 400, $message = null)
{
// check if $message is object and transforms it into an array
if (is_object($message)) { $message = $message->toArray(); }

switch ($code) {
default:
$code_message = 'error_occured';
break;
}

$data = array(
'code' => $code,
'message' => $code_message,
'data' => $message
);

// return an error
return Response::json($data, $code);
}

How to send Laravel error responses as JSON

I came here earlier searching for how to throw json exceptions anywhere in Laravel and the answer set me on the correct path. For anyone that finds this searching for a similar solution, here's how I implemented app-wide:

Add this code to the render method of app/Exceptions/Handler.php

if ($request->ajax() || $request->wantsJson()) {
return new JsonResponse($e->getMessage(), 422);
}

Add this to the method to handle objects:

if ($request->ajax() || $request->wantsJson()) {

$message = $e->getMessage();
if (is_object($message)) { $message = $message->toArray(); }

return new JsonResponse($message, 422);
}

And then use this generic bit of code anywhere you want:

throw new \Exception("Custom error message", 422);

And it will convert all errors thrown after an ajax request to Json exceptions ready to be used any which way you want :-)

Forcing json responses for API not working on laravel 8

The response helper can be used to generate other types of response instances. The json method will automatically set the Content-Type header to application/json

return response()->json([
'success' => true,
'message' => 'Hello world',
]);

I show an example applied to a validation

public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email'
]);

if($validator->fails()) {
return response()->json([
'success' => false,
'message' => $validator->errors()
], 422);
}

# other instructions ...
}

how return validation rules and messages as JSON for API in laravel 8

It should not be necessary to pass the validation messages to the JSON response. When the validation fails Laravel will automatically return the response with the errors and not continue executing the code in the controller.

There are pre-defined validation error messages that can also be localized. You can find them in resources/lang/en/validation.php - consider putting your custom messages there too.

To retrieve the validation errors as JSON add in the header of the request the key Accept with the value application/json

Response JSON error - Type is not supported when using Eloquent

The error message Type is not supported is actually coming from PHP's JSON serializer. There are only a very few types that PHP cannot serialise and the one that seems to be causing the issue in your particular case is a stream resource.

In order to check what is actually serialized in your model you will need to call:

$user = UserSecurity::where('userName', $userName)->get();
$user->map->jsonSerialize()->dd();

jsonSerialize exists because all Laravel models implement the JsonSerializable interface.

This will dump a collection of arrays of what PHP will attempt to serialise as JSON. The contents of this array are recursively serialised.

The default implementation of JsonSerializable in Model will attempt to serialize all model attributes but first will attempt to cast and call all accessors on attributes. This may or may not cause issues. At any rate the solution here is to figure out why there's a resource being returned in the jsonSerialize method and figure out the best way to hide it. Normally you can hide attributes by using

protected $hidden = [ 'timestamp' ];

however from your question it seems that the answer may not be so straight forward so may need to dig deeper.

return errors while using API routes in Laravel 8

It is redirecting back to "/" because $request->validate() method throws \Illuminate\Validation\ValidationException exception..

There are try ways to handle this request.

  1. Put try catch block around your validate code
  2. Or Handle this expection in app\Exception\Handler.php, and return the response in JSON format.



Related Topics



Leave a reply



Submit