问题:
How can I return the List<DataStruture> error codes in a spring ExceptionHandler class? I tried the below code:
@ExceptionHandler({ CustomException.class })
@Respon...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
How can I return the List<DataStruture>
error codes in a spring ExceptionHandler
class? I tried the below code:
@ExceptionHandler({ CustomException.class })
@ResponseStatus(HttpStatus.CONFLICT)
public List<ErrorOutDTO> handle(CustomException theException) {
return new null;
}
I was struck at the return type of a method.
回答1:
You should bind List of errors in ResponseEntity and then return it.
@ExceptionHandler(CustomException.class)
public ResponseEntity<List<ErrorOutDTO>> validationExceptionHandler(CustomException exception) {
List<ErrorOutDTO> list = new ArrayList<>();
ErrorOutDTO error = new ErrorOutDTO();
error.setField(exception.getField());
error.setMessage(exception.getMessage());
list.add(error);
return (ResponseEntity<List<ErrorOutDTO>>)new ResponseEntity(list, HttpStatus.CONFLICT);
}
回答2:
For example, if exception is ConstrainViolationException: This exception reports the result of constraint violations
@ExceptionHandler({ ConstraintViolationException.class })
public ResponseEntity<Object> handleConstraintViolation(
ConstraintViolationException ex, WebRequest request) {
List<String> errors = new ArrayList<String>();
for (ConstraintViolation<?> violation : ex.getConstraintViolations()) {
errors.add(violation.getRootBeanClass().getName() + " " +
violation.getPropertyPath() + ": " + violation.getMessage());
}
ApiError apiError =
new ApiError(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), errors);
return new ResponseEntity<Object>(
apiError, new HttpHeaders(), apiError.getStatus());
}