实现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";
}
}
评论区