首页 > 其他分享 >自定义异常处理

自定义异常处理

时间:2023-01-15 17:56:21浏览次数:45  
标签:自定义 处理 writer httpServletResponse HttpServletResponse json 异常 public

1. MyAccessDeniedHandler类

@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        //响应状态
        httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
        //返回json格式
        httpServletResponse.setHeader("Content-Type","application/json;charset=utf-8");
        PrintWriter writer = httpServletResponse.getWriter();
        writer.write("{\"status\":\"error\",\"msg\":\"权限不足\"}");
        writer.flush();
        writer.close();
    }
}

2.SecurityConfig类中config方法

//异常处理
http.exceptionHandling()
                .accessDeniedHandler(myAccessDeniedHandler);

标签:自定义,处理,writer,httpServletResponse,HttpServletResponse,json,异常,public
From: https://www.cnblogs.com/lwx11111/p/17053843.html

相关文章