侧边栏壁纸
博主头像
会飞的大象博主等级

爱运动的程序猿

  • 累计撰写 124 篇文章
  • 累计创建 162 个标签
  • 累计收到 1 条评论
标签搜索

目 录CONTENT

文章目录

springboot 针对http请求401,404,500状态码处理

会飞的大象
2022-07-27 / 0 评论 / 0 点赞 / 525 阅读 / 178 字

实现ErrorController完成对401,404,405异常拦截,并处理成json或html页面返回

package cn.byzk.appsignservice2.common.config.web;

import cn.byzk.appsignservice2.common.enums.http.ResultEnum;
import cn.byzk.appsignservice2.common.exception.SysException;
import org.apache.ibatis.exceptions.PersistenceException;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 会飞的大象 2022-07-27
 */
@RestController
public class PageController implements ErrorController {

    // 500跳转
    @RequestMapping("/error")
    //返回值为String 可以返回到指定页面
    public void sysError(HttpServletRequest request){
        //获取statusCode:401,404,500
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");
        if (throwable.getCause().getCause() instanceof PersistenceException)
        {
            throw new SysException(ResultEnum.DATABASE_ERROR);
        }else {
            throw  new SysException(statusCode,throwable.getCause().getMessage());
        }


    }

    @Override
    public String getErrorPath() {
        return "/error";
    }
}

0

评论区