Spring Boot开发Restful API中异常和错误处理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a2011102394/article/details/80669075

Spring Boot中默认的错误处理机制

在客户端的错误处理

在浏览器端的错误处理

可以看出,在浏览器发出的请求,出现错误返回的是一段html页面,而在app端发生错误请求时,返回的是一段json数据。

这是因为在Spring Boot 内部对请求会进行判断,进而做出相应的不同的响应

具体的实现可以查看BasicErrorController(在IDEA中搜索类的快捷键Ctrl+Shift+T),如下:

关于HTTP请求中的content-type和SpringMVC中的相关注解,可以参考

https://blog.csdn.net/shinebar/article/details/54408020

查看之前通过浏览器和app发出的请求

浏览器请求

app请求

自定义异常处理

  1. 自定义异常(以用户不存在为例)

    @Getter
    @Setter
    public class UserNotExitException extends RuntimeException {
    
    
        /**
         * 用户id
         */
        private String id;
    
        public UserNotExitException(String id){
            super("user not exit");
            this.id = id;
        }
    
    }
    
  2. 在Controller中的相应的方法中进行异常的抛出

  3. 统一管理Controller中抛出的异常

    /**
     * 〈一句话功能简述〉<br>
     * 〈控制器的错误处理器〉
     *  只用来处理其他Controller抛出的异常,
     *  本身并不处理Http请求
     * @create 2018/6/12 10:21
     * @since 1.0.0
     */
    @ControllerAdvice
    public class ControllerExceptionHandler {
    
        /**
         * 处理用户不存在的异常
         * @param ex 抛出的异常
         * @return
         */
        @ExceptionHandler(UserNotExitException.class)
        @ResponseBody
        @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
        public Map<String,Object> handleUserNotExitException(UserNotExitException ex){
            Map<String,Object> result = new HashMap<>();
            result.put("id",ex.getId());
            result.put("massage",ex.getMessage());
            return  result;
        }
    
    }
    

猜你喜欢

转载自blog.csdn.net/a2011102394/article/details/80669075