谷粒学苑 统一异常处理

1.Result类

package com.example.commonutils;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class Result {
    private String message;

    private boolean successs;

    private int code;

    private Object data;



    public static Result success(Object data){
        return new Result("success",true,200,data);
    }

    public static Result fail(String message,int code){
        return new Result(message,false,code,null);
    }
}

2。异常类

package com.example.servicebase.exceptionhandler;

import com.example.commonutils.R;
import com.example.commonutils.Result;
import com.example.commonutils.ResultCode;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GuLiExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result get(Exception e){
        e.printStackTrace();
        return Result.fail("执行了全局处理异常", ResultCode.ERROR);
    }
}

3.测试

@GetMapping("getTeacher/{id}")
    public R getTeacher(@PathVariable String id){
        EduTeacher eduTeacher = eduTeacherService.getById(id);
        int i = 3/0;
        try{
        }catch (Exception e){
//           throw new GuLiException(ResultCode.ERROR,"执行了自定义异常");
//            GuLiException guLiException = new GuLiException();
//            guLiException.setMsg("执行了自定义异常");
//            guLiException.setCode(ResultCode.ERROR);
//            throw guLiException;
        }
        return R.ok().data("teacher",eduTeacher);
    }

3.访问 http://localhost:8001/eduservice/teacher/getTeacher/1
浏览器显示
{“message”:“执行了全局处理异常”,“successs”:false,“code”:20001,“data”:null}

4.特定异常

package com.example.servicebase.exceptionhandler;

import com.example.commonutils.R;
import com.example.commonutils.Result;
import com.example.commonutils.ResultCode;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GuLiExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result get(Exception e){
        e.printStackTrace();
        return Result.fail("执行了全局处理异常", ResultCode.ERROR);
    }

    @ExceptionHandler(ArithmeticException.class)
    @ResponseBody
    public Result get(ArithmeticException e){
        e.printStackTrace();
        return Result.fail("执行了ArithmeticException异常处理",ResultCode.ERROR);
    }
}

5.访问 http://localhost:8001/eduservice/teacher/getTeacher/1
浏览器显示
{“message”:“执行了ArithmeticException异常处理”,“successs”:false,“code”:20001,“data”:null}

二。自定义异常
1.R类

package com.example.commonutils;

import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.util.HashMap;
import java.util.Map;
@Data
public class R{
    @ApiModelProperty(value="是否成功")
    private Boolean success;

    @ApiModelProperty(value="返回码")
    private Integer code;

    @ApiModelProperty(value="返回消息")
    private String message;

     private String problemLocation;

    @ApiModelProperty(value="返回数据")
    private  Map<String,Object> data=new HashMap<String,Object>();

    private R(){}

    public static R ok(){
        R r=new R();
        r.setSuccess(true);
        r.setCode(ResultCode.SUCCESS);
        r.setMessage("成功");
        System.out.println(r);
        return r;
    }

    public static R error(){
        R r = new R();
        r.setSuccess(false);
        r.setCode(ResultCode.ERROR);
        r.setMessage("失败");
        return r;
    }

    public R success(Boolean success){
        this.setSuccess(success);
        return this;
    }

    public R code(Integer code){
        this.setCode(code);
        return this;
    }

    public R message(String message){
        this.setMessage(message);
        return this;
    }

    public R problemLocation(String problemLocation){
        this.setProblemLocation(problemLocation);
        return this;
    }



    public R data(String key,Object value){
        this.data.put(key,value);
        System.out.println("this="+this);
        return this;
    }

    public R data(Map<String,Object> map){
        this.setData(map);
        return this;
    }


}

2.异常类

package com.example.servicebase.exceptionhandler;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class GuLiException extends RuntimeException{
    private Integer code;
    private String msg;
    private String problemLocation;
}

3.异常处理类

package com.example.servicebase.exceptionhandler;

import com.example.commonutils.R;
import com.example.commonutils.Result;
import com.example.commonutils.ResultCode;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GuLiExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result get(Exception e){
        e.printStackTrace();
        return Result.fail("执行了全局处理异常", ResultCode.ERROR);
    }

    @ExceptionHandler(ArithmeticException.class)
    @ResponseBody
    public Result get(ArithmeticException e){
        e.printStackTrace();
        return Result.fail("执行了ArithmeticException异常处理",ResultCode.ERROR);
    }

    @ExceptionHandler(GuLiException.class)
    @ResponseBody
    public R get(GuLiException exception){
        StackTraceElement[] stackTrace = exception.getStackTrace();
        String problemLocation = null;
        for (StackTraceElement stackTraceElement : stackTrace) {
             problemLocation = "异常发生在"+stackTraceElement+"处";
            System.out.println("____________________"+stackTraceElement);
            break;
        }
        return R.error().code(exception.getCode()).message(exception.getMsg()).problemLocation(problemLocation);
    }

}

4.抛出异常

@GetMapping("getTeacher/{id}")
    public R getTeacher(@PathVariable String id){
        EduTeacher eduTeacher = eduTeacherService.getById(id);
        try{
            int i = 3/0;
        }catch (Exception e){
//           throw new GuLiException(ResultCode.ERROR,"执行了自定义异常");
            GuLiException guLiException = new GuLiException();
            guLiException.setMsg("执行了自定义异常");
            guLiException.setCode(ResultCode.ERROR);
            throw guLiException;
        }
        return R.ok().data("teacher",eduTeacher);
    }

5.访问 http://localhost:8001/eduservice/teacher/getTeacher/1
浏览器显示
{“success”:false,“code”:20001,“message”:“执行了自定义异常”,“problemLocation”:“异常发生在com.example.eduservice.controller.EduTeacherController.getTeacher(EduTeacherController.java:185)处”,“data”:{}}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值