zoukankan      html  css  js  c++  java
  • SpringBoot自定义异常和自定义返回格式(例如token)便于前端接收抛出

    有的时候对于一些特殊的异常,我们需要进行别人的处理,那怎么自定义我们的异常的?

    //这里可继承你需要定义的错误
    public class CustomException extends RuntimeException {
    
        //可以用来接受我们方法中传的参数
        private String code;
        private String msg;
    
        public CustomException(String code,String msg) {
            //super("Token异常,请重新登录");
            this.code = code;
            this.msg=msg;
        }
    
    
        public String getCode() {
            return code;
        }
    
        public void setCode(String code) {
            this.code = code;
        }
    
        public String getMsg() {
            return msg;
        }
    
        public void setMsg(String msg) {
            this.msg = msg;
        }
    }

    在你需要的地方直接抛出这个异常
     	if (token == null||token.equals("")) {
                   //throw new RuntimeException("未认证,请检查token,请重新登录");
                   logger.error("401未认证请检查token");
                    throw new CustomException("401","未认证请检查token");
             }

    这个接口是要给app调用的,对于app来说需要定义统一的接受格式,不然没有办法拿到返回的数据,所以我们需要定义自己的异常返回类型

    import org.springframework.http.HttpStatus;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.bind.annotation.ResponseStatus;
    
    import java.util.HashMap;
    import java.util.Map;
    
    @ControllerAdvice
    public class ControllerHanderException {
        @ExceptionHandler(CustomException.class)
        @ResponseBody
        @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
        //在这个方法里定义我们需要返回的格式
        public Map<String, Object> handleUserNotExistException(CustomException ex){
            Map<String, Object> result = new HashMap<>();
            result.put("code", ex.getCode());  //获取到我们定义的code
            result.put("msg", ex.getMsg());		//获取到我们定义的msg
            //result.put("message", ex.getMessage());
            return result;
        }
    
    }

    @ControllerAdvice注解表示这个Controller不处理http请求,只处理当其他controller抛出异常时,进行处理。

    @ExceptionHandler: 就是定义处理什么异常

    在这里插入图片描述

  • 相关阅读:
    socketpair和pipe的区别
    C++异常与析构函数及构造函数
    System v shm的key
    不可靠信号SIGCHLD丢失的问题
    非阻塞IO函数
    Android 编译时出现r cannot be resolved to a variable
    找工作笔试面试那些事儿(5)---构造函数、析构函数和赋值函数
    unable to load default svn client 和 Eclipse SVN 插件与TortoiseSVN对应关系
    演示百度地图操作功能
    求第i个小的元素 时间复杂度O(n)
  • 原文地址:https://www.cnblogs.com/dzcWeb/p/13935368.html
Copyright © 2011-2022 走看看