Spring Boot 3 新增 ControllerAdvice 错误处理类 ProblemDetail

Spring Boot About 1,714 words

说明

Spring 6.0Spring Boot 3)后新增的类。

源码

注入ProblemDetailsExceptionHandler对象,ResponseEntityExceptionHandler对象默认是不注入的,ResponseEntityExceptionHandler中定义了各种错误处理

// org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration.ProblemDetailsErrorHandlingConfiguration
public class WebMvcAutoConfiguration {

    @Configuration(proxyBeanMethods = false)
    @ConditionalOnProperty(prefix = "spring.mvc.problemdetails", name = "enabled", havingValue = "true")
    static class ProblemDetailsErrorHandlingConfiguration {

        @Bean
        @ConditionalOnMissingBean(ResponseEntityExceptionHandler.class)
        ProblemDetailsExceptionHandler problemDetailsExceptionHandler() {
            return new ProblemDetailsExceptionHandler();
        }

    }
」

属性配置类

@ConfigurationProperties(prefix = "spring.mvc")
public class WebMvcProperties {
    public static class Problemdetails {

        /**
         * Whether RFC 7807 Problem Details support should be enabled.
         */
        private boolean enabled = false;

        public boolean isEnabled() {
            return this.enabled;
        }

        public void setEnabled(boolean enabled) {
            this.enabled = enabled;
        }

    }
}

开启 ProblemDetail

默认为false

spring:
  mvc:
    problemdetails:
      enabled: true

返回值示例

Content-Typeapplication/problem+json

状态码:500

字段:typetitlestatusinstance

POST http://localhost:8080/api/login

HTTP/1.1 500 
Content-Type: application/problem+json
Transfer-Encoding: chunked
Date: Sun, 29 Jan 2023 04:01:16 GMT
Connection: close

{
  "type": "/api/login",
  "title": "Internal Server Error",
  "status": 500,
  "instance": "/api/login"
}

RFC 7807

https://datatracker.ietf.org/doc/html/rfc7807

Views: 1,308 · Posted: 2023-01-29

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh