spring @ControllerAdvice 异常处理程序方法不会被调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16582411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
@ControllerAdvice exception handler method are not get called
提问by Vishal Singh
I have following controller class
我有以下控制器类
package com.java.rest.controllers;
@Controller
@RequestMapping("/api")
public class TestController {
@Autowired
private VoucherService voucherService;
@RequestMapping(value = "/redeemedVoucher", method = { RequestMethod.GET })
@ResponseBody
public ResponseEntity redeemedVoucher(@RequestParam("voucherCode") String voucherCode) throws Exception {
if(voucherCode.equals( "" )){
throw new MethodArgumentNotValidException(null, null);
}
Voucher voucher=voucherService.findVoucherByVoucherCode( voucherCode );
if(voucher!= null){
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json; charset=utf-8");
voucher.setStatus( "redeemed" );
voucher.setAmount(new BigDecimal(0));
voucherService.redeemedVoucher(voucher);
return new ResponseEntity(voucher, headers, HttpStatus.OK);
}
else{
throw new ClassNotFoundException();
}
};
}
}
And for exception handling I am using Spring3.2 advice handler as follow
对于异常处理,我使用 Spring3.2 建议处理程序如下
package com.java.rest.controllers;
@ControllerAdvice
public class VMSCenteralExceptionHandler extends ResponseEntityExceptionHandler{
@ExceptionHandler({
MethodArgumentNotValidException.class
})
public ResponseEntity<String> handleValidationException( MethodArgumentNotValidException methodArgumentNotValidException ) {
return new ResponseEntity<String>(HttpStatus.OK );
}
@ExceptionHandler({ClassNotFoundException.class})
protected ResponseEntity<Object> handleNotFound(ClassNotFoundException ex, WebRequest request) {
String bodyOfResponse = "This Voucher is not found";
return handleExceptionInternal(null, bodyOfResponse,
new HttpHeaders(), HttpStatus.NOT_FOUND , request);
}
}
}
I have defined XML bean definition as
我已经将 XML bean 定义定义为
<context:component-scan base-package="com.java.rest" />
Exception thrown from controller are not handled by controller advice handler. I have googled for hours but could not find any reference why it is happening. I followed as described http://www.baeldung.com/2013/01/31/exception-handling-for-rest-with-spring-3-2/here.
从控制器抛出的异常不会由控制器建议处理程序处理。我已经用谷歌搜索了几个小时,但找不到任何参考为什么会发生这种情况。我按照http://www.baeldung.com/2013/01/31/exception-handling-for-rest-with-spring-3-2/中的描述进行操作。
If anybody knows about please let know why handler is not handling exception.
如果有人知道,请告诉为什么处理程序没有处理异常。
回答by Vishal Singh
I found the solution for the above problem. Actually @ControllerAdvice needs MVC namespace declaration in XML file. Or we can use @EnableWebMvc with @ControllerAdvice annotation.
我找到了上述问题的解决方案。实际上@ControllerAdvice 需要在 XML 文件中声明 MVC 命名空间。或者我们可以使用带有@ControllerAdvice 注释的@EnableWebMvc。
回答by Evgeni Atanasov
I had similar problem.
我有类似的问题。
Managed to fix it in September 2017.
设法在 2017 年 9 月修复了它。
My case was that the Exception handler was in its own com.example.Exceptions package, and the problem was it was not scanned by Spring ComponentScan.
我的情况是异常处理程序在它自己的 com.example.Exceptions 包中,问题是它没有被 Spring ComponentScan 扫描。
Solution is to add it in the ComponentScan like so:
解决方案是将其添加到 ComponentScan 中,如下所示:
@ComponentScan({ "x.y.z.services", "x.y.z.controllers", "x.y.z.exceptions" })
回答by Mustafa Gen?
public class VMSCenteralExceptionHandler implements HandlerExceptionResolver {
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
}
}
and add your bean into your config.xml
并将您的 bean 添加到您的 config.xml 中
<bean class="com.java.rest.controllers.VMSCenteralExceptionHandler " />
回答by Hiren
You just need to perform these 2 steps :
您只需要执行以下 2 个步骤:
- Add @ControllerAdviceon top of the global exception handler class.
Add your package name of exception class in component-scan i.e.
<context:component-scan base-package="com.hr.controller,com.hr.exceptions" />
- 在全局异常处理程序类之上添加@ControllerAdvice。
在组件扫描 ie 中添加您的异常类的包名称
<context:component-scan base-package="com.hr.controller,com.hr.exceptions" />
回答by CorayThan
I think the problem is probably that your controller method throws Exceptionbut your @ControllerAdvicemethods catch specific exceptions. Either combine them into one handler that catches Exception, or make your controller throw those specific exceptions.
我认为问题可能是您的控制器方法抛出Exception但您的@ControllerAdvice方法捕获特定异常。要么将它们组合成一个捕获 的处理程序Exception,要么让您的控制器抛出这些特定的异常。
So your controller method signature should be:
所以你的控制器方法签名应该是:
public ResponseEntity redeemedVoucher(@RequestParam("voucherCode") String voucherCode) throws MethodArgumentNotValidException, ClassNotFoundException;
OR your controller advice should only have one method with the annotation:
或者您的控制器建议应该只有一种带有注释的方法:
@ExceptionHandler({
Exception.class
})

