不会调用@ControllerAdvice异常处理程序方法 [英] @ControllerAdvice exception handler method are not get called
问题描述
我有以下控制器类
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();
}
};
}
对于异常处理,我正在使用Spring3.2建议处理程序,如下所示
And for exception handling I am using Spring3.2 advice handler as follow
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);
}
}
我已将XML bean定义定义为
I have defined XML bean definition as
<context:component-scan base-package="com.java.rest" />
从控制器引发的异常未由控制器建议处理程序处理.我已经搜索了几个小时,但找不到任何参考来说明为什么会发生这种情况. 我按照所述> ://www.baeldung.com/2013/01/31/exception-handling-for-rest-with-spring-3-2/此处.
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.
如果有人知道,请告诉我们处理程序为什么不处理异常.
If anybody knows about please let know why handler is not handling exception.
推荐答案
我找到了上述问题的解决方案.实际上@ControllerAdvice需要XML文件中的MVC名称空间声明.或者我们可以将@EnableWebMvc与@ControllerAdvice批注一起使用.
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异常处理程序方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!