日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

spring boot 异常处理

發(fā)布時間:2025/3/21 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 spring boot 异常处理 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

spring?boot在異常的處理中,默認實現(xiàn)了一個EmbeddedServletContainerCustomizer并定義了一個錯誤頁面到”/error”中,在ErrorMvcAutoConfiguration源碼中可以看到

/*** {@link EmbeddedServletContainerCustomizer} that configures the container's error* pages.*/ private static class ErrorPageCustomizerimplements EmbeddedServletContainerCustomizer, Ordered {private final ServerProperties properties;protected ErrorPageCustomizer(ServerProperties properties) {this.properties = properties;}@Overridepublic void customize(ConfigurableEmbeddedServletContainer container) {container.addErrorPages(new ErrorPage(this.properties.getServletPrefix()+ this.properties.getError().getPath()));}@Overridepublic int getOrder() {return 0;}}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

還配置了一個默認的白板頁面,在源碼可以看到

@Configuration @ConditionalOnProperty(prefix = "server.error.whitelabel", name = "enabled", matchIfMissing = true) @Conditional(ErrorTemplateMissingCondition.class) protected static class WhitelabelErrorViewConfiguration {private final SpelView defaultErrorView = new SpelView("<html><body><h1>Whitelabel Error Page</h1>"+ "<p>This application has no explicit mapping for /error, so you are seeing this as a fallback.</p>"+ "<div id='created'>${timestamp}</div>"+ "<div>There was an unexpected error (type=${error}, status=${status}).</div>"+ "<div>${message}</div></body></html>");@Bean(name = "error")@ConditionalOnMissingBean(name = "error")public View defaultErrorView() {return this.defaultErrorView;}// If the user adds @EnableWebMvc then the bean name view resolver from// WebMvcAutoConfiguration disappears, so add it back in to avoid disappointment.@Bean@ConditionalOnMissingBean(BeanNameViewResolver.class)public BeanNameViewResolver beanNameViewResolver() {BeanNameViewResolver resolver = new BeanNameViewResolver();resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 10);return resolver;}}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

在路徑的處理上,定義了一個BasicErrorController來處理異常,ErrorAttributes來裝載錯誤異常到前端

@Controller @RequestMapping("${server.error.path:${error.path:/error}}") public class BasicErrorController extends AbstractErrorController {private final ErrorProperties errorProperties;//...@RequestMapping(produces = "text/html")public ModelAndView errorHtml(HttpServletRequest request,HttpServletResponse response) {response.setStatus(getStatus(request).value());Map<String, Object> model = getErrorAttributes(request,isIncludeStackTrace(request, MediaType.TEXT_HTML));return new ModelAndView("error", model);}@RequestMapping@ResponseBodypublic ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {Map<String, Object> body = getErrorAttributes(request,isIncludeStackTrace(request, MediaType.ALL));HttpStatus status = getStatus(request);return new ResponseEntity<Map<String, Object>>(body, status);}//... }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

默認只要你請求的content-type是”text/html”則返回一個白版頁面給你,如果是其他的content-type,則返回一個json的數(shù)據(jù)給你。

若你想自定義異常,可以通過以下方式來處理

1.你可以默認在classpath:templates下定義一個error.ftl的freemarker模版來定義異常頁面

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body><h1> error page !! </h1>${timestamp?string('yyyy-MM-dd HH:mm:ss')}<br/><br/>${status} <br/><br/>${error} <br/><br/>${message} <br/><br/>${path} <br/><br/></body> </html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

2.可以利用@ExceptionHandler來為某個特定的controller攔截異常,并返回一個json數(shù)據(jù),當(dāng)然你也可以定義全部的controller來攔截異常

@ControllerAdvice(basePackageClasses = FooController.class) public class FooControllerAdvice extends ResponseEntityExceptionHandler {@ExceptionHandler(YourException.class)@ResponseBodyResponseEntity<?> handleControllerException(HttpServletRequest request, Throwable ex) {HttpStatus status = getStatus(request);return new ResponseEntity<>(new CustomErrorType(status.value(), ex.getMessage()), status);}private HttpStatus getStatus(HttpServletRequest request) {Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");if (statusCode == null) {return HttpStatus.INTERNAL_SERVER_ERROR;}return HttpStatus.valueOf(statusCode);}}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

3.還可以自定義server的錯誤頁面

@Bean public EmbeddedServletContainerCustomizer containerCustomizer(){return new MyCustomizer(); }// ...private static class MyCustomizer implements EmbeddedServletContainerCustomizer {@Overridepublic void customize(ConfigurableEmbeddedServletContainer container) {container.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/500"));}}

總結(jié)

以上是生活随笔為你收集整理的spring boot 异常处理的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。