请问laravel8.0中如何自定义异常错误信息

有一个问题,更新laravel8.0后,发现之前在laravel6.0中参考手摸手教你让 Laravel 开发 API 更得心应手给api做的自定义异常处理不能用了,原因是Exceptions目录中的helper文件发生了改变,看了github上的变动,原来是为了简化异常处理在laravel8.0中做了优化,那么现在问题来了,应该如何在laravel8.0中解决这个问题?

laravel6.0的贴图:

<?php

namespace App\Exceptions;

use App\Api\Helpers\ExceptionReport;
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * @param  \Exception  $exception
     * @return void
     *
     * @throws \Exception
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Symfony\Component\HttpFoundation\Response
     *
     * @throws \Exception
     */
    public function render($request, Exception $exception)
    {
//        return parent::render($request, $exception);
        //ajax请求我们才捕捉异常
        if ($request->ajax()){
             //将方法拦截到自己的ExceptionReport
            $reporter = ExceptionReport::make($exception);
            if ($reporter->shouldReturn()){
                return $reporter->report();
            }
            if(env('APP_DEBUG')){
                //开发环境,则显示详细错误信息
                return parent::render($request, $exception);
            }else{
                //线上环境,未知错误,则显示500
                return $reporter->prodReport();
            }
        }
}

laravel8.0代码贴图:

<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
  /**
 * A list of the exception types that are not reported. * * @var array
 */  protected $dontReport = [
  //
  ];

  /**
 * A list of the inputs that are never flashed for validation exceptions. * * @var array
 */  protected $dontFlash = [
  'password',
  'password_confirmation',
  ];

  /**
 * Register the exception handling callbacks for the application. * * @return void
 */  public function register()
 {  //
  }

}
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
讨论数量: 7
3年前 评论
FoldingFan (楼主) 3年前

实际上没什么影响好像,你还是能直接复写render

3年前 评论

file 改这里,不记得是哪个版本改了异常类的基类,可能还有个别地方要改,你找下

3年前 评论
test2018 3年前

也是直接 public function render($request, Throwable $e) 重写这个方法就好了。

3年前 评论

同问,如何自定义CSRF和具体到某一个MODE的404错误提示

2年前 评论

楼主解决了吗?@FoldingFan

2年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!