自定义Filter类中throw自定义异常,报错
相关截图:
Filter类:
public class UserFilter implements Filter { public static User user; @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response=(HttpServletResponse)servletResponse; response.setContentType("text/html;charset=UTF-8"); String token = request.getHeader(Constant.JWT_TOKEN); if (StringUtils.isEmpty(token)) { response.getWriter().println("{\n" + " \"status\": 305,\n" + " \"msg\": \"LOGIN_NOT(用户未登录)\",\n" + " \"data\": null\n" + "}"); response.getWriter().flush(); response.getWriter().close(); return; } Algorithm algorithm = Algorithm.HMAC256(Constant.JWT_KEY); JWTVerifier build = JWT.require(algorithm).build(); try { DecodedJWT verify = build.verify(token); user=new User(); user.setUsername(verify.getClaim(Constant.USER_NAME).asString()); user.setId(verify.getClaim(Constant.USER_ID).asInt()); } catch (TokenExpiredException e) { throw new UserException(EnumUtils.JWT_TOKEN_EXPIRED);//token过期. }catch (JWTDecodeException e) { throw new UserException(EnumUtils.JWT_DECODE_EXPIRED);//解析失败 } if (user == null) { response.getWriter().println("{\n" + " \"status\": 305,\n" + " \"msg\": \"LOGIN_NOT(用户未登录)\",\n" + " \"data\": null\n" + "}"); response.getWriter().flush(); response.getWriter().close(); return; } filterChain.doFilter(servletRequest,servletResponse); } @Override public void destroy() { } }
自定义异常类:
package com.example.bbs.exception; import com.example.bbs.utils.EnumUtils; import javax.annotation.Resource; public class UserException extends Exception { private final Integer code; private final String message; public UserException(EnumUtils exceptionEnum) { this(exceptionEnum.getCode(),exceptionEnum.getMsg() ); } public UserException(Integer code, String message) { this.code = code; this.message = message; } public Integer getCode() { return code; } public String getMessage() { return message; } }
枚举类:
package com.example.bbs.utils; import jdk.internal.org.objectweb.asm.tree.IincInsnNode; public enum EnumUtils { SUCCESS(200,"成功"), CREATE_FAILED(300,"用户创建失败"), REGISTER_FAILED(301,"用户名重复"), USER_NULL(302,"用户名为空"), PASSWORD_NULL(303,"密码为空"), LOGIN_FAULT(304,"用户名或密码错误"), LOGIN_NOT(305,"用户未登录"), INSERT_FAULT(400,"插入失败"), UPDATE_FAULT(401,"更新失败"), DELETE_FAULT(402,"删除失败"), JWT_TOKEN_EXPIRED(500,"Token过期"), JWT_DECODE_EXPIRED(501,"解码失败"), SYSTEM_ERROR(1000,"系统错误"); Integer code; String msg; EnumUtils(Integer code, String msg) { this.code = code; this.msg = msg; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
25
收起
正在回答 回答被采纳积分+1
1回答
相似问题
登录后可查看更多问答,登录/注册
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星