SpringBoot全局异常处理中心
为什么需要全局异常处理中心?
我们在开发web项目时,如果不对异常进行处理,那么程序出现异常,这些异常会展示给用户看到,这样子虽然对用户说没什么,但是这样的也太土了吧~~~
如何自定义全局异常处理中心?
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
1.自定义一个异常
public class ErrExcepotin extends RuntimeException{
private int i ;
public ErrExcepotin(int i){
this.i=i;
}
public int getErrCode(){
return i;
}
}
2.创建全局异常处理中心
@Configuration//把这个类作为配置类
@ControllerAdvice(annotations = {RestController.class, Controller.class})//那种情况下处理
@ResponseBody//处理放回的数据为json
public class GlobalException {
//自定义异常
@ExceptionHandler(ErrExcepotin.class)
public int testException(ErrExcepotin err){
return err.getErrCode();
}
//运行时异常
@ExceptionHandler(RuntimeException.class)
public String testException(RuntimeException run){
return "这是运行时异常";
}
}
3.测试全局异常
@RestController
public class testException {
@RequestMapping("test")
public void test(){
throw new ErrExcepotin(400);
}
@RequestMapping("testrun")
public void testrun(){
throw new RuntimeException();
}
}
4.测试结果
4.1自定义异常
4.2运行时异常
总结
全局异常处理中心就是把平时出现异常不友好提示转换了一下,实现过程主要是自己配置异常中心,在异常中心添加异常,然后对异常进行处理,并返回处理后的信息。对于自定义异常可根据自己的需求编写。