Laravel 9数据库连接失败时如何抛出自定义错误视图?
数据库连接失败时自定义错误视图的实现方案
ASP.NET(Core)环境
- 捕获数据库连接异常:在数据访问层或初始化代码中,捕获对应数据库的连接异常(比如SQL Server的
SqlException),通过错误码(如10061)判断是否为主动拒绝连接的场景。 - 准备自定义错误输出:要么直接输出
<h1>连接失败</h1>,要么创建仅包含该内容的视图文件(如ConnectionError.cshtml)。 - 配置全局异常处理:在
Program.cs中添加异常拦截逻辑,匹配到目标异常时返回自定义内容:app.UseExceptionHandler(errorApp => { errorApp.Run(async context => { var exception = context.Features.Get<IExceptionHandlerPathFeature>()?.Error; if (exception is SqlException sqlEx && sqlEx.Number == 10061) { context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable; await context.Response.WriteAsync("<h1>连接失败</h1>"); // 若使用视图,替换为:return View("ConnectionError"); } }); });
Spring Boot环境
- 全局异常拦截:使用
@ControllerAdvice定义全局异常处理器,捕获SQLException并判断异常信息关键词:@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(SQLException.class) public ResponseEntity<String> handleDbConnectionRefused(SQLException ex) { if (ex.getMessage().contains("actively refused it")) { return new ResponseEntity<>("<h1>连接失败</h1>", HttpStatus.SERVICE_UNAVAILABLE); } return new ResponseEntity<>("数据库异常", HttpStatus.INTERNAL_SERVER_ERROR); } } - 若使用视图渲染:创建
connection-error.html页面(仅含<h1>连接失败</h1>),修改处理器返回视图名:@ExceptionHandler(SQLException.class) public String handleDbConnectionView(SQLException ex) { return ex.getMessage().contains("actively refused it") ? "connection-error" : "error"; }
PHP(Laravel)环境
- 扩展异常处理器:在
app/Exceptions/Handler.php的register方法中添加自定义渲染逻辑:use Illuminate\Database\QueryException; use PDOException; $this->renderable(function (QueryException $e, $request) { if ($e->getPrevious() instanceof PDOException && str_contains($e->getMessage(), "actively refused it")) { return response()->view('connection-error', [], 503); } }); - 创建视图文件:在
resources/views下新建connection-error.blade.php,内容仅为<h1>连接失败</h1>。
内容的提问来源于stack exchange,提问作者Raitiko
相关产品推荐
相关产品推荐

