公司早期后端服务(nodejs),异常返回体如下:
{
"error_category": string,
"error_code": string,
"error_message": string,
"error_number": number,
"log_uuid": string
}
现在重构成 java,用的是 spring boot 。但是在异常处理这一块,要保持和之前一致。
spring 默认异常
接口定义
@GetMapping("/params-test")
String paramsTest(
@Valid @Min(1) @RequestParam("phone") String phone
) {
return phone;
}
在 postman 发起请求, 得到的响应结果如下
{
"timestamp": "2021-07-31T14:49:49.813+00:00",
"status": 400,
"error": "Bad Request",
"path": "/params-test"
}
预期的结果是
{
"error_message": "Required request parameter 'phone' for method parameter type String is not present",
"log_uuid": "a02ae7e7-761c-4de3-971f-0bf7df61be88",
"error_code": "A_5",
"error_number": 5,
"error_category": "A"
}
如何实现预期结果
- 定义一个异常处理类,并加上注解ControllerAdvice,当程序抛出异常时,就会执行 handleServletRequestBindingException,这时我们就可以定制化的输出异常信息了。
@ControllerAdvice
public class ApiExceptionHandler {
@ExceptionHandler({ MissingServletRequestParameterException.class })
public ResponseEntity<HashMap<String, Object>> handleServletRequestBindingException(MissingServletRequestParameterException ex, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
HashMap<String, Object> stringObjectHashMap = new HashMap<>();
stringObjectHashMap.put("error_code", "A_5");
stringObjectHashMap.put("error_category", "A");
stringObjectHashMap.put("error_number", 5);
stringObjectHashMap.put("error_message", ex.getMessage());
stringObjectHashMap.put("log_uuid", UUID.randomUUID().toString());
return new ResponseEntity<>(stringObjectHashMap, HttpStatus.BAD_REQUEST);
}
// 当然这里肯定还需要处理其他异常的
}
- 另外一种写法, 继承 ResponseEntityExceptionHandler, 并重写异常处理方法
@ControllerAdvice
public class ApiExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
HashMap<String, Object> stringObjectHashMap = new HashMap<>();
stringObjectHashMap.put("error_code", "A_5");
stringObjectHashMap.put("error_category", "A");
stringObjectHashMap.put("error_number", 5);
stringObjectHashMap.put("error_message", ex.getMessage());
stringObjectHashMap.put("log_uuid", UUID.randomUUID().toString());
return this.handleExceptionInternal(ex, stringObjectHashMap, headers, status, request);
}
// 建议这里复写其他异常处理方法,保持错误信息输出结构一致
}
网友评论