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: 就是定义处理什么异常

    在这里插入图片描述

  • 相关阅读:
    Running ASP.NET Applications in Debian and Ubuntu using XSP and Mono
    .net extjs 封装
    ext direct spring
    install ubuntu tweak on ubuntu lts 10.04,this software is created by zhouding
    redis cookbook
    aptana eclipse plugin install on sts
    ubuntu open folderpath on terminal
    ubuntu install pae for the 32bit system 4g limited issue
    EXT Designer 正式版延长使用脚本
    用 Vagrant 快速建立開發環境
  • 原文地址:https://www.cnblogs.com/dzcWeb/p/13935368.html
Copyright © 2011-2022 走看看