欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringMVC全局异常处理

程序员文章站 2022-04-21 23:49:05
...

1:引入springboot.jar

<parent>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-parent</artifactId>
   <version>2.0.5.RELEASE</version>
   <relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
   <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
   </dependency>
</dependencies>
2:定义异常类
public class GlobalException extends Exception {

    public GlobalException(String message){
        super(message);
    }

    public GlobalException(){
        super();
    }
}

3:定义Controller

@RestController
public class ErrorController {

    @GetMapping(value = "error1")
    public void error() throws Exception {
        throw new GlobalException("返回异常!");
    }

}

4:定义全局异常处理

@ControllerAdvice
public class BaseExceptionHandler {

    @ExceptionHandler(value = GlobalException.class)
    @ResponseBody
    public Result error(Exception e) {
        return new Result(false, 404, "全局"+e.getMessage());
    }
}

启动报错:

{"flag":false,"code":404,"message":"全局返回异常!","data":null}

OK!