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
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
<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.
If anybody knows about please let know why handler is not handling exception.
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.
I had similar problem.
Managed to fix it in September 2017.
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.
Solution is to add it in the ComponentScan like so:
@ComponentScan({ "x.y.z.services", "x.y.z.controllers", "x.y.z.exceptions" })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With