I have a controller to receive POST requests and return a JSON output. An exception handler which was implemented inside the controller class worked fine.
I have tried to add Global exception handling with @ControllerAdvice
annotation, but this doesn't work in my solution. I don't think the global exception handler class is being loaded.
Below is my controller class:
package hello;
@Controller
@RequestMapping("/v1")
public class MyController {
@RequestMapping(value = "/saveEmployee", method = RequestMethod.POST, produces = "application/json")
@ResponseBody
public String saveEmployee(@Valid @RequestBody Employee employee) {
return "{ \"name\":\"" + employee.getEmail() + "\"}";
}
}
Below is Global exception handler class:
package util;
@ControllerAdvice
public class MyControllerAdvice {
@ExceptionHandler(MethodArgumentNotValidException.class)
// @ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public String processValidationError(MethodArgumentNotValidException ex) {
BindingResult result = ex.getBindingResult();
FieldError fieldError = result.getFieldError();
String code = fieldError.getCode();
String field = fieldError.getField();
String message = fieldError.getDefaultMessage();
message = "{ \"Code\":\"" + code + "\",\"field\":\"" + field + "\",\"Message\":\"" + message + "\"}";
return message;
}
}
Below are my configurations:
package hello;
@SpringBootApplication
public class Application {
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
@Bean
public LocalValidatorFactoryBean validator() {
LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
bean.setValidationMessageSource(messageSource());
return bean;
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Spring boot version : 2.0.3.RELEASE
hello
whereas the exception handler in a package calledutil
. My first though is that you're not bringing the exception handler into context.