【问题标题】:Laravel 8: How to handle internal server error in api using postmanLaravel 8:如何使用邮递员处理 api 中的内部服务器错误
【发布时间】:2021-11-14 15:23:02
【问题描述】:

我想在我的邮递员中处理 500 Internal Server Error 作为 JSON 响应,请帮助我。

我在 Exception/Handler.php 中有这种代码,但我不知道如何处理在 POSTMAN 中返回 JSON 响应的 500 内部服务器错误。

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

【问题讨论】:

    标签: laravel api


    【解决方案1】:

    这是 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

    【讨论】:

    • 对于 API,您也应该始终使用错误处理程序。
    【解决方案2】:

    您可以轻松地在控制器中使用 try/catch,

    例如对于这段代码,看起来像这样, 并作为响应返回您想要的任何状态而不是服务器错误系列代码。

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

    【讨论】:

      猜你喜欢
      • 2015-02-14
      • 1970-01-01
      • 1970-01-01
      • 2020-07-27
      • 2017-05-05
      • 1970-01-01
      • 2018-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多