PHP causes Laravel to return custom errors for JSON REST API

  • 2021-11-10 08:57:56
  • OfStack

I am developing some kind of RESTful API. When I have one error, I will throw an App:: abort ($code, $message) error.

The problem is: I want him to throw an array of json with the keys "code" and "message", each containing the above data.


Array
(
  [code] => 401
  [message] => "Invalid User"
)

Does anyone know if it is possible, and if so, what should I do?

Fuck your app/start/global. php.

This will convert all errors in 401 and 404 to custom json errors instead of 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 for handling this error.

It is best to create your own helper for API, such as Responser:: error (400, 'damn'), which extends the Response class.

Kind of 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);
}

Summarize


Related articles: