我有以下控制器类@ControllerAdvice异常处理方法不会被调用
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意见处理程序遵循
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定义为
<context:component-scan base-package="com.java.rest" />
从控制器抛出的异常不由控制器建议处理程序处理。我已经搜索了几个小时,但没有找到任何参考它为什么发生。 我跟着描述http://www.baeldung.com/2013/01/31/exception-handling-for-rest-with-spring-3-2/在这里。
如果有人知道请告诉我们为什么handler没有处理异常。
为了进一步澄清这个答案,ResponseEntityExceptionHandler的子类必须包含在@ComponentScan的顺序路径Spring容器检测到它。我不认为这个文件很清楚。希望这能为一些人节省一些时间。 – cwu9T9
你能否澄清你的意思是“需要MVC命名空间声明”? –
@EricB。通过MVC命名空间声明,我的意思是,我们应该在我们的配置xml文件(例如applicationConfig.xml)中具有 。如果我们不在xml文件中使用 ,那么我们必须使用带有ControllerAdvice批注的EnableWebMvc。 –