我有以下控制器類@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。 –