Issue
I am developing a spring boot app with restful services and angularjs as front end. The application must support multiple languages. One of the things I am having problem is the business exceptions thrown from my services. E.g. I have a book service which may throw an exception like this
if (book == null) {
throw new ServiceException("The book you are looking for no longer exist");
}
What is the best approach to localize them?
Solution
You have to use @RestControllerAdvice to seprate your exception handling logic from your business code. As per @ControllerAdvice doc, the methods defined in the class annotated as @ControllerAdvice apply globally to all Controllers. @RestControllerAdvice is just a convenience class equal to (@RestControllerAdvice = @ControllerAdvice + @ResponseBody). Please check below class:
@RestControllerAdvice
public class GenericExceptionHandler {
@Autowired
private MessageSource messageSource;
@ExceptionHandler(ServiceException.class)
public ResponseEntity<ErrorResponse> handle(ServiceException.class e, Locale locale) {
String errorMessage = messageSource.getMessage(
"error.message", new Object[]{},locale);
ErrorResponse error = new ErrorResponse();
error.setErrorCode(HttpStatus.BAD_REQUEST.value());
error.setMessage(errorMessage);
return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
}
}
// other Custom Exception handlers
Your ErrorResponse is normal javabean as below:
public class ErrorResponse{
private int errorCode;
private String message;
//getter and setter
}
And you should have MessageSource configured in your configuration to read the locale specific error messages as below:
@Configuration
public class MessageConfig {
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource source = new ResourceBundleMessageSource();
source.setBasename("i18n/messages");
source.setUseCodeAsDefaultMessage(true);
return source;
}
}
Answered By - Sangam Belose
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.