springboot 异常处理最佳实践

通常情况下,在一个系统中,抽象出公用的部分的过程是一个DRY的一个过程。这是所有计算机工程中的一个准则。防止重复是各种轮子的开始。

springboot 异常处理

springboot常用的异常处理是利用@ControllerAdvice或者@RestControllerAdvice编写的,这两个注解的作用均是在Runtime时期。这个类会捕获在Controller中抛出的异常,这样就可以极大的简化controller中出现的杂乱的异常代码,遇到异常只需要抛出,在共有的异常处理类中就会处理。

代码如下:

@RestControllerAdvice
public class GlobalExceptionHandler {
    
}

常见异常分类

在常见的HTTP Restful请求中,所有抛出的异常都要有对应的http code来对应。常见的HTTP状态码有:

  • 200 成功 通常的成功响应都返回这个HTTP状态码
  • 201 创建 通常在创建应用成功之后会返回这个HTTP状态码
  • 404 找不到,通常在查询对象无法找到的时候返回这个HTTP状态码,这个是最常用的异常响应
  • 500 内部错误 通常在服务器内部出现错误的时候,比如逻辑异常的时候返回500错误
  • 401 请求未授权 通常在没有通过服务器鉴权的时候会抛出这个状态码
  • 403 禁止 通常在没有认证的时候返回这个状态码
  • 409 冲突 通常在新增对象的时候,如果已经存在这个对应的对象就会返回这个状态码,比如新增对象ID冲突

401和403的区别在于403是认证,比如用户密码错误这属于认证失败,返回403。而如果在登录之后,访问某些资源,但是没有权限,这属于鉴权失败,返回401。

对应的异常处理代码如下:

404异常:

    /**
     * 响应码 404 找不到
     *
     * @param e
     * @return
     */
    @ExceptionHandler({NoSuchStudentException.class})
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ResponseBody
    public VndErrors onNotFoundException(Exception e) {
        String logRef = logWarnLevelExceptionMessage(e);
        if (log.isTraceEnabled()) {
            logTraceLevelStrackTrace(e);
        }
        String msg = getExceptionMessage(e);
        return new VndErrors(logRef, msg);
    }

409 冲突错误异常,经常用在新增或修改的时候

    /**
     * 响应码 409 对象已经存在,冲突错误
     *
     * @param e
     * @return
     */
    @ExceptionHandler(AllReadyExistsStudentException.class)
    @ResponseStatus(HttpStatus.CONFLICT)
    @ResponseBody
    public VndErrors onAllReadyExistsException(Exception e) {
        String logRef = logWarnLevelExceptionMessage(e);
        if (log.isTraceEnabled()) {
            logTraceLevelStrackTrace(e);
        }
        String msg = getExceptionMessage(e);
        return new VndErrors(logRef, msg);
    }

500内部错误异常

    /**
     * 响应码 500 内部错误
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public VndErrors onException(Exception e) {
        log.error("Caught exception while handling a request", e);
        String logRef = e.getClass().getSimpleName();
        String msg = getExceptionMessage(e);
        return new VndErrors(logRef, msg);
    }

这些都是一些异常的案例,可以参考编写自己的异常处理,异常处理在遇到对应的@ExceptionHandler时候,如果已经在对应的ExceptionHandler中存在,就会按照这个注解下的方法进行异常处理,如果没有,就会继续往上抛出,在上述代码案例中,可以看到500内部错误异常的代码@ExceptionHandler(Exception.class)使用的是Exception类,这样的话,所以没有被其他@ExceptionHandler处理或者尚未编写的异常处理,都会按照HTTP状态码500这个代码来处理。

所以,在真实的业务场景下,尽可能将自己的业务异常补充到对应HTTP状态码的异常处理方法中,这样就会在Restful的API中,让状态码发挥自己的应有的意义。而不是仅仅抛出一个错误.

VndErrors 和HATEOAS

查看上述代码的时候发现在异常处理的时候,返回了一个VndErrors对象,这个属于Springboot hateoas,具体可以参考springboot HATEOAS实践这篇文章,总而言之,这是一个异常处理的返回对象,并且是一个最佳实践的异常处理返回对象。

springboot统一返回对象

定义好异常之后,在对应的controller中就需要编写自己的代码逻辑,无非是常见的几个HTTP请求方法的注解

@GetMapping

@PostMapping

@PutMapping

@DeleteMapping

还有一个不常用的@PatchMapping在大多数时候使用@PutMapping替代。

代码如下:

  • Get请求 查询

        /**
         * 根据Id查询学生
         *
         * @param id 忽略大小写
         * @return 学生信息
         */
        @GetMapping("/{id}")
        public ResponseEntity getStudentByName(@PathVariable int id) {
            return studentService.getStudentById(id).map(ResponseEntity::ok).orElseThrow(() -> new NoSuchStudentException(String.valueOf(id)));
        }
    
    
  • Post请求 新增

        /**
         * 新增学生
         *
         * @param studentFromRequest 学生对象
         * @return 新增的学生的信息
         */
        @PostMapping
        public ResponseEntity addStudent(@RequestBody Student studentFromRequest) {
            if (studentService.getStudentById(studentFromRequest.getId()).isPresent()) {
                throw new AllReadyExistsStudentException(studentFromRequest.getId());
            }
            return new ResponseEntity<>(studentService.addStudent(studentFromRequest), HttpStatus.CREATED);
        }
    
    
  • Put请求 修改

        /**
         * 修改学生信息
         *
         * @param studentFromRequest 学生对象
         * @return 修改的学生的信息
         */
        @PutMapping
        public ResponseEntity modifyStudent(@RequestBody Student studentFromRequest) {
            if (studentService.getStudentById(studentFromRequest.getId()).isPresent()) {
                throw new AllReadyExistsStudentException(studentFromRequest.getId());
            }
            val student = studentService.addStudent(studentFromRequest);
            return new ResponseEntity<>(student, HttpStatus.CREATED);
        }
    
    
  • Delete请求 删除

        /**
         * 根据Id删除学生
         *
         * @param id 学生姓名 忽略大小写
         * @return
         */
        @DeleteMapping("/{id}")
        public ResponseEntity deleteStudentById(@PathVariable int id) {
            return studentService.getStudentById(id).map(p -> {
                studentService.deleteStudentById(id);
                return ResponseEntity.noContent().build();
            }).orElseThrow(() -> new NoSuchStudentException(String.valueOf(id)));
        }
    

上述代码采用了Java8的一些特性,可以参考 Java8,Java9,Java10新语法特性来了解更多

全部代码

全部代码已经上传到Github上,可以参考springboot-restful

你可能感兴趣的:(springboot 异常处理最佳实践)