1. 程式人生 > >SpringBoot全域性異常捕捉

SpringBoot全域性異常捕捉

在一個專案中的異常我們我們都會統一進行處理的,那麼如何進行統一進行處理呢? 新建一個類GlobalDefaultExceptionHandler, 在class註解上@ControllerAdvice, 在方法上註解上@ExceptionHandler(value = Exception.class),具體程式碼如下:

com.kfit.base.exception.GlobalDefaultExceptionHandler
package com.kfit.base.exception;

import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice public class GlobalDefaultExceptionHandler { @ExceptionHandler(value = Exception.class) public void defaultErrorHandler(HttpServletRequest req, Exception e) { // // If the exception is annotated with @ResponseStatus rethrow it and
let // // the framework handle it - like the OrderNotFoundException example // // at the start of this post. // // AnnotationUtils is a Spring Framework utility class. // if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) // throw e; // // // Otherwise setup and
send the user to a default error-view. // ModelAndView mav = new ModelAndView(); // mav.addObject("exception", e); // mav.addObject("url", req.getRequestURL()); // mav.setViewName(DEFAULT_ERROR_VIEW); // return mav; //列印異常資訊: e.printStackTrace(); System.out.println("GlobalDefaultExceptionHandler.defaultErrorHandler()"); /* * 返回json資料或者String資料: * 那麼需要在方法上加上註解:@ResponseBody * 新增return即可。 */ /* * 返回檢視: * 定義一個ModelAndView即可, * 然後return; * 定義檢視檔案(比如:error.html,error.ftl,error.jsp); * */ } } com.kfit.test.web.DemoController 加入方法: @RequestMapping("/zeroException") public int zeroException(){ return 100/0; }