springboot 全局異常處理

springboot 全局異常處理

研究了半天springboot的全局異常處理,雖然仍是須要再多整理一下,可是對於常見的404和500足以能夠區分開,可以根據這兩個異常分別處理web

首先配置視圖解析路徑

spring.mvc.view.prefix=/WEB-INF/
spring.mvc.view.suffix=.jsp

針對500錯誤

建立單獨的配置類,放在啓動類同包或子包下

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalDefaultExceptionHandler {
    

    //能夠返回自定義的錯誤頁面
    @ExceptionHandler(Exception.class)  //這裏根據報的異常能夠寫不一樣的方法,反別捕捉
    private ModelAndView returnErrorPage(Exception e) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("exception",e.getClass().getName());
        mv.setViewName("/error");
        return mv;
    }
}

針對404錯誤

一樣建立單獨的配置類,放在啓動類同包或子包下

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("error")
public class MyErrorController implements ErrorController {
    
    Logger logger = LoggerFactory.getLogger(MyErrorController.class);
    
    @Override
    public String getErrorPath() {
        logger.info("********************進入自定義異常********************");
        return "err";   //這個返回的視圖名稱不要用error,springboot默認的視圖名是error,若是必定要用error,須要將error放在指定的路徑下,這個往後再整理。
    }
    
    @RequestMapping
    public String error() {
        return getErrorPath();
    }

}
相關文章
相關標籤/搜索