ControllerAdvice
@ControllerAdviceSpring 3.2 provides a new annotation, which is a Controller enhancer that adds some logic to the methods annotated by @RequestMapping in the controller. The most common one is exception handling
2: @controlleradvice with exception handler
When throwing exceptions to the controller, you can unify the exception handling by specifying the returned json format or jumping to an error page
3: Examples
@Slf4j
@ControllerAdvice
public class ExceptionHandlerAdvice {
@ResponseStatus(HttpStatus.OK)
@ResponseBody
@ExceptionHandler({MethodArgumentNotValidException.class})
public <T> ResponseEntity<ResultDTO<T>> handleBusinessException(MethodArgumentNotValidException method) {
String defaultMessage = method.getBindingResult().getFieldError().getDefaultMessage();
log.error("Error in parameters: {}", defaultMessage);
return ResponseEntity.ok(ResultDTO.getErrorResult(defaultMessage));
}
@ResponseStatus(HttpStatus.OK)
@ResponseBody
@ExceptionHandler(ValidationException.class)
public <T> ResponseEntity<ResultDTO<T>> handleBusinessException(ValidationException exception) {
String defaultMessage = exception.getMessage();
log.error("Error in parameters,{}", defaultMessage);
return ResponseEntity.ok(ResultDTO.getErrorResult(defaultMessage));
}
}
Read More:
- Realize the simplest recursive call, simulate exception in thread “main” java.lang.stackoverflowerror exception
- Solved: elasticsearch error: exception [type = search]_ phase_ execution_ exception, reason=all shards failed]
- The solution of a Java exception has occurred. And error exception in thread when eclipse runs
- Window installation of MongoDB exception: connect failed exception
- How to Fix error performing isolated work; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarE
- How to handle exception in springboot
- Exception handling of httpmessage notwritableexception in springboot
- Python keyerror exception
- Analysis of shadows a parameter exception in C + +
- java.lang.IllegalArgumentException : urlcoder exception resolution
- Cause check of unreachable statement exception in Java
- Springboot project startup exception – required a single bean, but 2 were found
- Resolve rabbitmq declarationexception: failed to declare queue exception
- Exception of browser accessing servlet404
- Default constructor cannot handle exception type FileNotFoundException thrown by implicit super cons
- Java class file operation and exception
- Java retainAll throws an unsupported operation exception record
- Springboot startup error – classnotfound Exception:EnhancerBySpringCGLIB
- Unsatisfied dependencyexception exception
- Parsing the exception of storing JSON string in cookie