如何修改Spring Boot 3.x中Problem Detail API的默认type字段值?
如何修改Spring Boot 3.x中Problem Detail API的默认type字段值?
嗨,我来帮你搞定这个问题!在Spring Boot 3.x里修改Problem Detail API默认的about:blank类型值,有两种比较常用的方式,按需选择就好:
方法一:全局统一配置,覆盖所有Problem Details的type
这种方式适合你想给所有错误响应统一设置自定义type的场景,只需要实现ProblemDetailsCustomizer接口并注册成Bean就行:
import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.http.HttpStatus import org.springframework.web.servlet.mvc.method.annotation.ProblemDetailsCustomizer import java.net.URI @Configuration class ProblemDetailsConfig { @Bean fun customProblemDetailsCustomizer(): ProblemDetailsCustomizer { return ProblemDetailsCustomizer { problemDetails -> // 可以根据状态码区分设置不同type,比如给400错误单独指定 if (problemDetails.status == HttpStatus.BAD_REQUEST.value()) { problemDetails.type = URI.create("https://your-domain.com/problems/invalid-request") } // 如果想给所有错误统一设置,直接写下面这行就行 // problemDetails.type = URI.create("https://your-domain.com/problems/generic-error") } } }
启动项目后,所有符合条件的Problem Details响应都会自动替换掉默认的about:blank。
方法二:针对特定异常精细定制
如果你想给不同的错误场景(比如请求体解析失败、参数校验失败)设置不同的type,用@ControllerAdvice来处理特定异常是更灵活的方式。比如针对你遇到的请求体解析失败场景,可以这样写:
import com.fasterxml.jackson.databind.JsonParseException import org.springframework.http.HttpStatus import org.springframework.http.ProblemDetails import org.springframework.web.bind.annotation.ControllerAdvice import org.springframework.web.bind.annotation.ExceptionHandler import java.net.URI @ControllerAdvice class CustomProblemDetailsHandler { // 处理JSON解析失败的异常 @ExceptionHandler(JsonParseException::class) fun handleJsonParseError(ex: JsonParseException): ProblemDetails { val problemDetails = ProblemDetails.forStatus(HttpStatus.BAD_REQUEST) problemDetails.type = URI.create("https://your-domain.com/problems/invalid-json-body") problemDetails.title = "无效的JSON请求体" problemDetails.detail = "请求体解析失败:${ex.localizedMessage}" // 还可以额外添加自定义字段,比如错误位置 problemDetails.setProperty("error-location", ex.location?.toString()) return problemDetails } // 如果你还想处理参数校验失败的情况,可以加这个方法 // import org.springframework.web.bind.MethodArgumentNotValidException // @ExceptionHandler(MethodArgumentNotValidException::class) // fun handleValidationError(ex: MethodArgumentNotValidException): ProblemDetails { // val problemDetails = ProblemDetails.forStatus(HttpStatus.BAD_REQUEST) // problemDetails.type = URI.create("https://your-domain.com/problems/validation-failure") // problemDetails.title = "参数校验失败" // problemDetails.detail = "存在无效的请求参数" // // 把具体的校验错误返回给前端 // problemDetails.setProperty("invalid-fields", ex.bindingResult.fieldErrors.map { "${it.field}: ${it.defaultMessage}" }) // return problemDetails // } }
这样当你发送格式错误的JSON请求时,返回的Problem Details里的type就会变成你自定义的地址,同时还能定制更友好的title和detail信息。
备注:内容来源于stack exchange,提问作者Johan
相关产品推荐
相关产品推荐

