Spring Exception handler return list of errorcodes

问题: 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());
}
  • 发表于 2019-03-21 16:38
  • 阅读 ( 196 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除