Laravel 错误处理:抛出 404/403/500 异常
在Laravel框架中,处理HTTP异常可以通过创建自定义异常处理器来实现。以下是如何为常见的404、403、500错误创建自定义处理器的示例。
- 创建自定义异常处理器:
// app/Exceptions/Handler.php
public function render($request, Throwable $exception)
{
if ($exception instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) {
return response()->view('errors.404', [], 404);
}
if ($exception instanceof \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException) {
return response()->view('errors.403', [], 403);
}
if ($exception instanceof \ErrorException) {
return response()->view('errors.500', [], 500);
}
return parent::render($request, $exception);
}
- 创建相应的错误视图模板:
<!-- resources/views/errors/404.blade.php -->
<!DOCTYPE html>
<html>
<head>
<title>Page Not Found</title>
</head>
<body>
<h1>404 Error - Page Not Found</h1>
<p>The page you are looking for might have been removed, had its name changed, or is temporarily unavailable.</p>
</body>
</html>
<!-- resources/views/errors/403.blade.php -->
<!DOCTYPE html>
<html>
<head>
<title>Forbidden</title>
</head>
<body>
<h1>403 Error - Forbidden</h1>
<p>You don't have permission to access this resource on the server.</p>
</body>
</html>
<!-- resources/views/errors/500.blade.php -->
<!DOCTYPE html>
<html>
<head>
<title>Internal Server Error</title>
</head>
<body>
<h1>500 Error - Internal Server Error</h1>
<p>The server encountered a problem and could not complete your request.</p>
</body>
</html>
这样,当Laravel应用程序遇到上述异常时,会返回自定义的错误页面。记得在实际部署时,确保配置了正确的错误报告级别以及存储了错误日志,以便于调试和修复问题。
评论已关闭