java - 以同样的方式处理所有错误
问题描述
我用一个实体创建了简单的 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 相同的方式处理它们,我是否需要其他自定义验证器?
解决方案
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);
}
}
推荐阅读
- c# - 即使设置了权限,UWP 应用程序也无法访问 USB 驱动器
- python - Tensorflow“用于语言理解的变压器模型”与另一个数据集?
- java - 向界面装饰器模式添加功能
- javascript - 从标准 html 传递道具以反应组件
- c# - 无法从 MongoDB.Driver for C# 访问 MongoCollection 类
- linux-kernel - bpf_prog_test_run() 导致意外的数据包数据
- javascript - justify-content 弹性框中的均匀间隔项目实际上并不适用于元素 | 反应JS
- python - Pyside6 中的 QUdpSocket 没有发出 readReady,而 QT C++ 应用程序中的等效代码运行良好
- flutter - 如何将firestore查询存储在变量中
- google-tag-manager - 通过标签管理器添加可编程搜索