PHP使Laravel为JSON REST API返回自定义错误的问题

作者:代码日志 时间:2023-11-24 06:57:32 

我正在开发某种RESTful API.发生一些错误时,我会抛出一个App :: abort($code,$message)错误.

问题是:我希望他用键“代码”和“消息”抛出一个json形成的数组,每个数组都包含上述数据.


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

有没有人知道是否可能,如果是,我该怎么做?

去你的app / start / global.php.

这将将401和404的所有错误转换为自定义json错误,而不是Whoops stacktrace.加这个:


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

这是处理此错误的众多选项之一.

制作API最好创建自己的帮助器,如Responser :: error(400,'damn'),扩展了Response类.

有点像:


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

总结

以上所述是小编给大家介绍的PHP使Laravel为JSON REST API返回自定义错误的解决方法,希望对大家有所帮助.

来源:https://codeday.me/bug/20181016/297099.html

标签:php,json,返回错误
0
投稿

猜你喜欢

  • go-cache的基本使用场景示例解析

    2023-08-06 00:52:02
  • CSS分栏布局的方法:绝对定位和浮动

    2009-04-30 13:10:00
  • ASP中的Debug类--VBScript

    2008-10-24 09:38:00
  • PHP 进程锁定问题分析研究

    2023-11-21 18:14:10
  • 35个Python编程小技巧

    2023-08-23 21:23:50
  • js自动闭合html标签(自动补全html标记)

    2023-08-25 07:06:35
  • asp彩色验证码的制作详解

    2007-09-18 13:22:00
  • JSP + Servlet实现生成登录验证码示例

    2023-06-27 02:47:59
  • Google的产品设计指导思想

    2008-03-23 14:15:00
  • 发个选星星打分/投票功能函数

    2008-05-22 12:38:00
  • MYSQL初学者使用指南[适用自己安装mysql者]

    2007-08-06 14:53:00
  • IE8网页显示不正常 用”兼容性视图”搞定

    2009-03-28 11:13:00
  • 用JavaScript实现PHP的urlencode与urldecode函数

    2023-11-23 08:18:14
  • SQLServer WITH 的用法

    2009-07-09 18:54:00
  • 去掉前面的0的sql语句(前导零,零前缀)

    2011-09-30 11:28:19
  • vuejs实现下拉框菜单选择

    2023-09-23 08:49:54
  • php+ajax无刷新上传图片实例代码

    2023-11-17 11:27:58
  • Javascript优化(文件瘦身)

    2008-06-02 13:20:00
  • asp中判断是否是手机浏览器以及手机类型

    2014-12-06 09:33:05
  • Go语言基于Socket编写服务器端与客户端通信的实例

    2023-07-12 08:44:11
  • asp之家 网络编程 m.aspxhome.com