版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
路径: 网站根目录/app/Exceptions/Handler.php
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Validation\ValidationException; // 后加的
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.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $exception
* @return void
*/
public function report(Exception $exception)
{
parent::report($exception);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $exception
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $exception)
{
return parent::render($request, $exception);
}
/**
* 重写该方法, 用于ajax返回json
*/
protected function invalidJson($request, ValidationException $exception)
{
// 1. 这里是报原来的错误, 即 FromRequest.php(自定义文件) 里自定义的错误
return response()->json([
'code' => 201,
'msg' => $exception->getMessage(),
'errors' => $exception->errors(),
]);
// 2. 这里是统一给一个错误, 不让错误报的那么明显
// return response()->json(showError('ajax_error'));
}
}
1.要先测试,具体的代码自行取舍!
2.感觉laravel原来的报错提示方式别扭, 用了ajax以后感觉好多了!