💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
SpringBoot 默认到`resources/templates/error/`目录下扫描错误的页面,并根据模板名称来映射对应的错误。如下: ``` 假设你创建了 resources/templates/error/4xx.html模板和resources/templates/error/404.html 如果发生精确的错误,如404,则采用404.html渲染错误数据,否则采用4xx.html ``` <br/> 所以定制错误页面的步骤如下: **1. 错误数据由DefaultErrorAttributes提供** ```java -----DefaultErrorAttributes----- errorAttributes.put("status", 999); // 状态码 errorAttributes.put("error", "None"); // 错误提示 errorAttributes.put("exception", error.getClass().getName()); // 异常对象 errorAttributes.put("message", message); // 消息 errorAttributes.put("errors", result.getAllErrors()); // jsr303数据校验错误提示 errorAttributes.put("trace", stackTrace.toString()); errorAttributes.put("path", path); errorAttributes.put("timestamp", new Date()); ``` **2. 定制错误页面** (1)*`resources/templates/error/404.html`* ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>404</title> </head> <body> <div>Status:[[${status}]]</div> <div>Error:[[${error}]]</div> <div>Exception:[[${exception}]]</div> <div>Message:[[${message}]]</div> <div>Errors:[[${errors}]]</div> <div>Trace:[[${trace}]]</div> <div>Path:[[${path}]]</div> <div>Timestamp:[[${timestamp}]]</div> </body> </html> ``` (2)*`resources/templates/error/4xx.html`* ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>4xx</title> </head> <body> <div>Status:[[${status}]]</div> <div>Error:[[${error}]]</div> <div>Exception:[[${exception}]]</div> <div>Message:[[${message}]]</div> <div>Errors:[[${errors}]]</div> <div>Trace:[[${trace}]]</div> <div>Path:[[${path}]]</div> <div>Timestamp:[[${timestamp}]]</div> </body> </html> ``` **3. 测试** 启动项目后访问一个不存在的地址 http://localhost:8080/abc 时,得到如下结果。 ![](https://img.kancloud.cn/31/51/3151667159d1df858ea573f0a57bf4a7_1561x319.jpg)