SpringMVC全局異常處理

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!

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章