laravel 接口异常错误返回json数据

  • 在laravel中默认返回的异常是html的形式展现在页面上面,当我们写接口的时候我们希望错误是一定的json进行展示我们就需要对异常类进行处理改造

找到文件Exceptions\Handler.phprender方法尽心重写

public function render($request, Exception $exception)
    {
    
    

        if ($request->is('api/*')) {
    
    
            $response = [];
            $error = $this->convertExceptionToResponse($exception);
            $e = FlattenException::create($exception);
            $response['status_code'] = $error->getStatusCode();
            $response['message'] = $error->getStatusText();
            $response['debug']['line'] = $e->getLine();
            $response['debug']['file'] = $e->getFile();
            $response['debug']['class'] = $e->getClass();
            $response['debug']['trace'] = $e->getTrace();
            return response()->json($response, $error->getStatusCode());
        } else {
    
    
            return parent::render($request, $exception);
        }

    }

这里我们接口的访问url为api开头,我们对接口进行过滤,web访问还是使用原来的默认方式

$error = t h i s − > c o n v e r t E x c e p t i o n T o R e s p o n s e ( this->convertExceptionToResponse( this>convertExceptionToResponse(exception);

这里能获取到 状态码和状态简易信息。注意是convertExceptionToResponse返回的是response类,但是response类里面并没有getStatusText()方法,但是这个类里面有这个成员变量,这个时候我们需要重写这个类。

  • 新建APIResponse类来集成response类,新增 getStatusText() 方法
<?php
namespace App\Exceptions;
use Symfony\Component\HttpFoundation\Response;

class ApiResponse extends Response
{
    
    
    /**
     *获取statusText
     */

    public function getStatusText()
    {
    
    
        return $this->statusText;
    }

}

render 方法中重写convertExceptionToResponse 换成ApiResponse

 protected function convertExceptionToResponse(Exception $e)
    {
    
    

        $e = FlattenException::create($e);

        $handler = new SymfonyExceptionHandler(config('app.debug', false));

        return ApiResponse::create($handler->getHtml($e), $e->getStatusCode(), $e->getHeaders());
    }

当接口出错就能返回我们希望得到的json结果

在这里插入图片描述

Guess you like

Origin blog.csdn.net/weixin_43674113/article/details/119382458