Exception

异常是程序在编译或执行的过程中可能出现的问题;

1. Error:是一种错误,所有的错误只要发生,就会终止程序。错误是不能被处理的。2. Execption

        a. RuntimeException:运行时异常,指程序在运行时会出现的异常,在编写阶段程序员可以预先处理,也可以不管;比如NullPointerException(空指针异常)、FileNotFoundException(文件未找到异常)、ClassCastException(类型强化转换异常)等异常。

        b. 非运行时异常:即编译时异常,指在编译时必须处理的异常,如果不处理编译器报错。

1. try{} catch{}

try {
	// 代码逻辑。
} catch (Exception e) {
	// 可以选择需要捕获的异常,比指定相关逻辑,抛出异常、打印错误日志等等。
} finally {
	// 不管try 中是否发送异常,该逻辑都会被执行。
}

finally:在finally子句中的代码是最后执行的,并且是 一定会执行 的,即使try语句块中的代码出现了异常。finally子句必须和try一起出现,不能单独编写 

2. throw:指定异常,new throw IOEx;

if (StringUtils.isBlank(detailId)) {
    throw new RuntimeException("detailId is not null");
}

3. throws:抛出异常,可以在方法使用,表示此方法不处理此异常;

public OrderDetail findOrderDetailById(String detailId) throws Exception{
    return orderDetailMapper.findOrderDetailById(detailId);
}

自定义异常

创建异常类

public class SellException extends RuntimeException {
    private Integer code;
    public SellException(ResultEnum resultEnum) {
        super(resultEnum.getMessage());
        this.code = resultEnum.getCode();
    }
    public SellException(Integer code,String message) {
        super(message);
        this.code = code;
    }
    public Integer getCode() {
        return code;
    }
}

创建枚举,并通过枚举来指定异常

public enum ResultEnum {
    SUCCESS(0,"成功"),
    LOGIN_SUCCESS(1,"登出成功"),
    ORDER_NOT_EXIST(2, "查不到订单");
    
    private Integer code;
    private String message;
    
    public Integer getCode() {
        return code;
    }
    public String getMessage() {
        return message;
    }
    ResultEnum(Integer code, String message) {
        this.code = code;
        this.message = message;
    }
}

测试

if (orderId == null){
    throw new SellException(ResultEnum.ORDER_NOT_EXIST);
}

全局异常

 @RestControllerAdvice (拦截异常并统一处理):它通常用于定义@ExceptionHandler, @InitBinder 和 @ModelAttribute 适用于所有@RequestMapping方法的方法;

@RestControllerAdvice
public class ExceptionHandlerController {

    /**
     * 应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        System.out.println("binder.getFieldDefaultPrefix: " + binder.getFieldDefaultPrefix());
        System.out.println("binder.getFieldMarkerPrefix: " + binder.getFieldMarkerPrefix());
    }
    //把值绑定到Model中,使全局@RequestMapping可以获取到该值
    @ModelAttribute
    public void addAttributes(Model model) {
        model.addAttribute("author", "harry");
    }

    /**
     * 全局异常捕捉处理
     */
    @ExceptionHandler(RRException.class)
    public Reslut apiExceptionHandler(RRException ex) {
        System.out.println("ApiException 异常抛出:" + ex);
        return R.fail(ex);
    }

}

异常处理类

public class RRException extends RuntimeException {
	private static final long serialVersionUID = 1L;
    private String msg;
    private int code = 500;
    public RRException(String msg) {
		super(msg);
		this.msg = msg;
	}
	public RRException(String msg, Throwable e) {
		super(msg, e);
		this.msg = msg;
	}
	public RRException(String msg, int code) {
		super(msg);
		this.msg = msg;
		this.code = code;
	}
	public RRException(String msg, int code, Throwable e) {
		super(msg, e);
		this.msg = msg;
		this.code = code;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	public int getCode() {
		return code;
	}
	public void setCode(int code) {
		this.code = code;
	}
}
public class Reslut {

    private Integer code;

    private boolean success;

    private String message;

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}
public class R {

    public static Reslut fail(RRException e){
        Reslut reslut = new Reslut();
        reslut.setCode(e.getCode());
        reslut.setMessage(e.getMsg());
        reslut.setSuccess(false);
        return reslut;
    }

}

 测试

if (id == null) {
    throw new RRException("id不能为空!");
}
返回的格式
{
    "code": 500,
    "success": false,
    "message": "id不能为空!"
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值