Springboot中的全局处理机制(三)自定义异常处理

  //分页查询功能
    @ApiOperation(value = "根据讲师进行分页查询")
    @GetMapping("pageTeacher/{current}/{limit}")
    public R pageTeacher(@ApiParam(name = "current", value = "当前页码", required = true) @PathVariable long current,
                         @ApiParam(name = "limit", value = "每条记录数", required = true) @PathVariable long limit) {
        Page<EduTeacher> teacherPage = new Page<EduTeacher>(current, limit);

        try {
            int i=1/0;
        } catch (Exception e) {
            throw  new MyException(20001,"执行了自定义异常处理....");
        }
        eduTeacherService.page(teacherPage, null);

        long total = teacherPage.getTotal();
        List<EduTeacher> records = teacherPage.getRecords();

        return R.ok().data("total", total).data("records", records);

    }

先自定义异常类

package com.wgl.servicebase.exceptionhandler;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.jdbc.IncorrectResultSetColumnCountException;

/**
 * @author 万葛亮
 * @Date 2020 06 13 21:13
 */
@Data//生成get,set方法
@AllArgsConstructor//有参构造方法
@NoArgsConstructor//无参构造方法
public class MyException extends RuntimeException {

    private Integer code;//状态码
    private String msg;//异常信息
}
这是自己编写的异常处理程序
 //自定义异常
    @ResponseBody//返回数据
    @ExceptionHandler(MyException.class)//
    public R error(MyException e) {
        e.printStackTrace();
        return R.error().code(e.getCode()).message(e.getMsg());
    }

执行结果
Springboot中的全局处理机制(三)自定义异常处理_第1张图片

Springboot中的全局处理机制(三)自定义异常处理_第2张图片

你可能感兴趣的:(异常处理,Java)