美文网首页
重构 - 异常处理

重构 - 异常处理

作者: ithankzc | 来源:发表于2021-08-01 12:26 被阅读0次

    公司早期后端服务(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"
    }
    

    如何实现预期结果

    1. 定义一个异常处理类,并加上注解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);
        }
    
       // 当然这里肯定还需要处理其他异常的
    }
    
    1. 另外一种写法, 继承 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);
       }
    
       // 建议这里复写其他异常处理方法,保持错误信息输出结构一致
    }
    

    相关文章

      网友评论

          本文标题:重构 - 异常处理

          本文链接:https://www.haomeiwen.com/subject/fnzkvltx.html