You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 06:15:37