Throw new CustomerException('Customer message');
// App\Exceptions\Handler.php public function render($request, Exception $e) { // 没有权限访问 if ($e instanceof ForbiddenException) { $message = $e->getMessage() ?: '您没有权限操作'; $code = $e->getCode() ?: 401; $redirect = $e->getRedirect() ?: route('error.401'); return $request->ajax() || $request->wantsJson() ? response()->json([ 'message' => $message ], $code) : response(view('errors.401', compact('code', 'message', 'redirect')), $code); } // FirstOrFail 和 FindOrFail 异常处理 if ($e instanceof ModelNotFoundException) { // 如果删除的内容已经不存在了,就没必要报错了,直接成功处理 if ('DELETE' === strtoupper(Request::method())) { return Response::json([ 'success' => true ]); } if ($request->ajax() || $request->wantsJson()) { return response()->json([ 'message' => '没有找到' ], 404); } else { return response()->view('errors.404', [ ], 404); } } }