SpringBoot统一错误处理

1.处理错误请求页面

 

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.ErrorController;
/** 
*
@author SimonHu
* @Description:
* @Created on 2018/7/11 10:46
*/
@Controller @RequestMapping(value = "error")
public class BaseErrorController implements ErrorController {
@Value(
"${siteConfig.html_base_path}")
private String html_base_path;
private static final Logger logger = LoggerFactory.getLogger(BaseErrorController.class);
@Override
public String getErrorPath() { logger.error("出错啦2!进入自定义错误控制器");
//默认返回错误页面,自定义;
return "process/process"; } @RequestMapping public String error(HttpServletResponse response) throws IOException { return getErrorPath(response); } public String getErrorPath(HttpServletResponse response) throws IOException { logger.error("出错啦1!进入自定义错误控制器");
//重定向到新的页面,请求url response.sendRedirect(html_base_path
+"design/showMyWorks"); return ""; } }

 2.全局错误处理

import com.zhx.commonentity.CommonResult;
import com.zhx.constants.CodeMsgEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @author SimonHu
 * @Description:
 * @Created on 2018/6/25 10:15
 */
@ControllerAdvice
public class GlobalDefultExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalDefultExceptionHandler.class);
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public CommonResult defultExcepitonHandler(HttpServletRequest request, Exception e) {
        logger.error("错误信息:",e);
        return CommonResult.result(CodeMsgEnum.SYS_ERROR.getCode(),CodeMsgEnum.SYS_ERROR.getMsg());
    }
}

借鉴:https://blog.csdn.net/zhaozhirongfree1111/article/details/72526885

转载于:https://www.cnblogs.com/SimonHu1993/p/9293451.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值