问题Spring Web是一组库,可轻松从Spring应用程序中产生application/problem+json响应。它填充了一个利基市场,因为它连接了问题库以及Spring Web MVC的异常处理或Spring Webflux的异常处理,因此它们可以无缝地工作,同时需要最少的额外开发人员工作。这样一又一劳永逸地,它旨在执行一项小而重复的任务。
该库的工作方式基于我们所谓的建议特征。建议性状是一个小的,可重复使用的@ExceptionHandler ,该特征是在单个方法接口中放置的默认方法。这些建议特征可以自由组合,也不需要为您的@ControllerAdvice使用普通基类。
?请查看Baeldung:问题的指南Spring Web库,以详细介绍!
AdviceTrait提供的问题处理过程的构建方式是在需要时允许自定义的。可以通过实现适当的建议性状界面来自定义以下所有方面(以及更多):
| 方面 | 方法) | 默认 |
|---|---|---|
| 创建 | AdviceTrait.create(..) | |
| 记录 | AdviceTrait.log(..) | 4xx作为WARN ,5xx作为ERROR ,包括堆栈跟踪 |
| 内容谈判 | AdviceTrait.negotiate(..) | application/json , application/*+json , application/problem+json和application/x.problem+json |
| 倒退 | AdviceTrait.fallback(..) | application/problem+json |
| 后处理 | AdviceTrait.process(..) | N/A。 |
以下示例通过在Problem中添加parameter扩展字段来自定义MissingServletRequestParameterAdviceTrait :
@ ControllerAdvice
public class MissingRequestParameterExceptionHandler implements MissingServletRequestParameterAdviceTrait {
@ Override
public ProblemBuilder prepare ( Throwable throwable , StatusType status , URI type ) {
var exception = ( MissingServletRequestParameterException ) throwable ;
return Problem . builder ()
. withTitle ( status . getReasonPhrase ())
. withStatus ( status )
. withDetail ( exception . getMessage ())
. with ( "parameter" , exception . getParameterName ());
}
}假设有这样的控制器:
@ RestController
@ RequestMapping ( "/products" )
class ProductsResource {
@ RequestMapping ( method = GET , value = "/{productId}" , produces = APPLICATION_JSON_VALUE )
public Product getProduct ( String productId ) {
// TODO implement
return null ;
}
@ RequestMapping ( method = PUT , value = "/{productId}" , consumes = APPLICATION_JSON_VALUE )
public Product updateProduct ( String productId , Product product ) {
// TODO implement
throw new UnsupportedOperationException ();
}
}以下HTTP请求将分别产生相应的响应:
GET /products/123 HTTP/1.1
Accept: application/xml HTTP/1.1 406 Not Acceptable
Content-Type: application/problem+json
{
"title" : " Not Acceptable " ,
"status" : 406 ,
"detail" : " Could not find acceptable representation "
} POST /products/123 HTTP/1.1
Content-Type: application/json
{} HTTP/1.1 405 Method Not Allowed
Allow: GET
Content-Type: application/problem+json
{
"title" : " Method Not Allowed " ,
"status" : 405 ,
"detail" : " POST not supported "
}在继续之前,请阅读有关Zalando/问题中的堆栈跟踪和因果链的部分。
如果要启用堆栈跟踪,请按以下方式配置您的ProblemModule :
ObjectMapper mapper = new ObjectMapper ()
. registerModule ( new ProblemModule (). withStackTraces ());默认情况下,问题的因果链被禁用,但如果需要,可以被覆盖:
@ ControllerAdvice
class ExceptionHandling implements ProblemHandling {
@ Override
public boolean isCausalChainsEnabled () {
return true ;
}
}请注意,由于您可以完全访问应用程序上下文,因此您可以将配置外部化为application.yml server.error.include-stacktrace
启用这两个功能,因果链和堆栈都将产生:
{
" title " : " Internal Server Error " ,
" status " : 500,
" detail " : " Illegal State " ,
" stacktrace " : [
" org.example.ExampleRestController.newIllegalState(ExampleRestController.java:96) " ,
" org.example.ExampleRestController.nestedThrowable(ExampleRestController.java:91) "
],
" cause " : {
" title " : " Internal Server Error " ,
" status " : 500,
" detail " : " Illegal Argument " ,
" stacktrace " : [
" org.example.ExampleRestController.newIllegalArgument(ExampleRestController.java:100) " ,
" org.example.ExampleRestController.nestedThrowable(ExampleRestController.java:88) "
],
" cause " : {
" title " : " Internal Server Error " ,
" status " : 500,
" detail " : " Null Pointer " ,
" stacktrace " : [
" org.example.ExampleRestController.newNullPointer(ExampleRestController.java:104) " ,
" org.example.ExampleRestController.nestedThrowable(ExampleRestController.java:86) " ,
" sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) " ,
" sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) " ,
" sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) " ,
" java.lang.reflect.Method.invoke(Method.java:483) " ,
" org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) " ,
" org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) " ,
" org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) " ,
" org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) " ,
" org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) " ,
" org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) " ,
" org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) " ,
" org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) " ,
" org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) " ,
" org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) " ,
" org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) " ,
" org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) " ,
" org.junit.runners.ParentRunner.run(ParentRunner.java:363) " ,
" org.junit.runner.JUnitCore.run(JUnitCore.java:137) " ,
" com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117) " ,
" com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234) " ,
" com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74) "
]
}
}
} Spring允许将@ControllerAdvice的范围限制为某个控制器的子集:
@ ControllerAdvice ( assignableTypes = ExampleController . class )
public final class ExceptionHandling implements ProblemHandling通过这样做,您将失去处理某些类型的异常的功能:
HttpRequestMethodNotSupportedExceptionHttpMediaTypeNotAcceptableExceptionHttpMediaTypeNotSupportedExceptionNoHandlerFoundException我们从春季继承了这一限制,因此建议使用不受限制的@ControllerAdvice 。
如果您有疑问,疑虑,错误报告等,请在此存储库的问题跟踪器中提交问题。
为了做出贡献,只需提出拉动请求,然后添加您添加或更改的简短描述(1-2个句子)。有关更多详细信息,请检查贡献指南。