请问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()
{ //
}
}
错误《Laravel 8 中文文档》
实际上没什么影响好像,你还是能直接复写render
也是直接 public function render($request, Throwable $e) 重写这个方法就好了。
同问,如何自定义CSRF和具体到某一个MODE的404错误提示
楼主解决了吗?@FoldingFan