zoukankan      html  css  js  c++  java
  • (03)使用SpringBoot自定义Restful风格异常处理,返回json格式数据

      SpringBoot定义了默认处理异常的机制,简单的说就是APP客户端访问默认返回json,浏览器访问默认返回错误页面。使用Restful风格开发,我们往往习惯处理异常时,返回json串。下面说说怎样使浏览器访问,默认返回json串。

      1、默认跳转页面

    @RestController
    @RequestMapping("/user")
    public class UserController {
    @GetMapping(
    "/exception/{id:\d+}") public User getUserInfo(@PathVariable String id){ throw new RuntimeException("user not exist"); } }

      浏览器测试:http://localhost/user/exception/1,跳转到错误页面,显示错误信息 user not exist

      

      2、自定义返回json格式数据

      自定义异常类UserNotExistException.java

    public class UserNotExistException extends RuntimeException {
        
        private static final long serialVersionUID = -6112780192479692859L;
        private String id;
    
        public UserNotExistException(String id) {
            super("user not exist");
            this.id = id;
        }
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
    }

      自定义异常处理类ControllerExceptionHandler.java

    @ControllerAdvice
    public class ControllerExceptionHandler {
    
        @ExceptionHandler(UserNotExistException.class)
        @ResponseBody
        @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
        public Map<String,Object> handlerUserNotExistException(UserNotExistException userNotExistException){
            Map<String,Object> map=new HashMap<>();
            map.put("id", userNotExistException.getId());
            map.put("message", userNotExistException.getMessage());
            return map;
        }
    }

      修改UserController.java中getUserInfo方法

    @GetMapping("/exception/{id:\d+}")
    public User getUserInfo(@PathVariable String id){
        throw new UserNotExistException(id);
    }

      浏览器测试:http://localhost/user/exception/1,返回json格式数据,显示错误信息

      

      说明:

      1)如果getUserInfo方法中抛出RuntimeException,依然跳转页面,因为在异常处理类中指定的异常类型是UserNotExistException。

      2)如果异常处理类中指定的异常类型是Exception,那么getUserInfo方法中抛出任何异常都会返回json格式数据。

      3)业务类中抛出的是异常处理类定义的类型或是定义类型的子类型,才会返回json格式数据。

      更多异常处理请看我的文章:Spring Boot之异常处理的两种方式Spring MVC之处理异常的两种方式及优先级

  • 相关阅读:
    wireshark安装
    高效使用搜索引擎
    MFC 网络编程 -- 总结
    MFC Grid control 2.27
    A Popup Progress Window
    Showing progress bar in a status bar pane
    Progress Control with Text
    Report List Controls
    第三方
    CBarChart柱形图类
  • 原文地址:https://www.cnblogs.com/javasl/p/12971925.html
Copyright © 2011-2022 走看看