自定义异常与全局异常处理

前言:在Java中要想创建自定义异常,需要继承Throwable或者他的子类Exception。

class WrongInputException extends Exception {  // 自定义的类
    WrongInputException(String s) {
        super(s);
    }
}
class Input {
    void method() throws WrongInputException {
        throw new WrongInputException("Wrong input"); // 抛出自定义的类
    }
}
class TestInput {
    public static void main(String[] args){
        try {
            new Input().method();
        }
        catch(WrongInputException wie) {
            System.out.println(wie.getMessage());
        }
    } 
}


1. SpringBoot实现全局异常处理

SpringBoot中有一个@ControllerAdvice的注解,使用该注解表示开启了全局异常的捕获,我们只需在自定义一个方法使用ExceptionHandler注解然后定义捕获异常的类型即可对这些捕获的异常进行统一的处理。

@ControllerAdvice
public class MyExceptionHandler {

    // 这段代码表示捕获Exception异常
    @ExceptionHandler(value =Exception.class)
	public String exceptionHandler(Exception e){
		System.out.println("未知异常!原因是:"+e);
       	return e.getMessage();
    }

}

一般来说,这样就能实现全局异常处理,不过开发中,我们往往想针对更详细的异常做出相应的处理,比如空指针异常,返回空指针异常提示信息,比如方法不存在,返回方法不存在的异常提示信息。



2. 基于SpringBoot实现更优雅的全局异常处理

https://www.cnblogs.com/xuwujing/p/10933082.html

原文地址:https://www.cnblogs.com/itlihao/p/14952662.html