首页 > 解决方案 > 以同样的方式处理所有错误

问题描述

我用一个实体创建了简单的 REST API

@Entity
public class Note {
@JsonIgnore
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

@NotBlank(message = "Given title is empty")
private String title;

@NotNull(message = "Given content is null")
private String content;

我使用了自定义异常处理程序

@ControllerAdvice
public class CustomGlobalExceptionHandler extends ResponseEntityExceptionHandler {

@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, 
HttpHeaders headers, HttpStatus status, WebRequest request) {
    Map<String,Object> body = new LinkedHashMap<>();
    body.put("timestamp", new Date());
    body.put("status",status.value());

    List<String> errors = ex.getBindingResult()
            .getFieldErrors()
            .stream()
            .map(DefaultMessageSourceResolvable::getDefaultMessage)
            .collect(Collectors.toList());

    body.put("errors", errors);

    return new ResponseEntity<>(body,headers,status);
}
}

从 Hibernate 验证器抛出的异常现在看起来像这样:

{
"timestamp": "2021-04-24T21:43:58.678+00:00",
"status": 400,
"errors": [
    "Given title is empty"
]
}

但是我抛出的其他异常看起来像这样

{
"timestamp": "2021-04-24T21:46:05.576+00:00",
"status": 400,
"error": "Bad Request",
"message": "Task with given id does not exist",
"path": "/api/notes/2"
 }

如何以与 Hibernate Validator 相同的方式处理它们,我是否需要其他自定义验证器?

标签: javaspringhibernateexception

解决方案


import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

@ControllerAdvice
public class CustomGlobalExceptionHandler extends ResponseEntityExceptionHandler {

    @Override
    protected ResponseEntity<Object> handleExceptionInternal(Exception ex, @Nullable Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
        Map<String, Object> _body = new LinkedHashMap<>();
        _body.put("timestamp", new Date());
        _body.put("status", status.value());
        _body.put("errors", ex.getMessage());
        return new ResponseEntity<>(body,headers,status);
    }

    @ExceptionHandler()
    protected ResponseEntity<Object> handleConflict(RuntimeException ex, WebRequest request) {
        return handleExceptionInternal(ex, ex.getMessage(), new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, request);
    }
}

推荐阅读