springboot异常处理:404,500

这里不做过多解释,具体看代码注释:

package me.ffs.www.app.controller.exception;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;

import com.github.gserv.serv.commons.util.JsonMapper;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * @author : lichenfei
 * @date : 2020年1月6日
 * @time : 下午1:16:51
 *       

* :全局异常处理404,500 */ @Controller @ControllerAdvice public class ExceptionController implements ErrorController { private static Logger logger = LoggerFactory.getLogger(ExceptionController.class); @Autowired private ErrorAttributes error;// 用来获取当前异常信息 @RequestMapping("error") // 这里的error不能修改,详情看BasicErrorController源码,主要用来捕获404异常 public String handleError(HttpServletRequest request, HttpServletResponse response) { WebRequest webRequest = new ServletWebRequest(request); Map<String, Object> error_attributes = error.getErrorAttributes(webRequest, false); logger.error("error---not found : {}", JsonMapper.toJsonString(error_attributes)); return "404"; } @Override public String getErrorPath() {// 用处不大 return "404"; } @ExceptionHandler(value = Exception.class) // 用来捕获500异常 public String error500(Exception exception) { logger.error("error : {}", exception); return "500"; } // ......more }

有问题的请在下方留言

你可能感兴趣的:(springboot)