妙用CommonException

编程入门 行业动态 更新时间:2024-10-09 02:21:51

<a href=https://www.elefans.com/category/jswz/34/1767141.html style=妙用CommonException"/>

妙用CommonException

在开发wawaji项目时,我们有个校验用户身份的逻辑。如果校验成功,返回用户信息;如果用户不存在,返回4001008;如果token失效,返回4001010;如果token不正确,返回4001011。
由于多处逻辑需要校验用户身份,所有我们希望在校验过程中,如果校验失败,直接返回失败结果,程序不再继续执行。
1.编写检验失败返回错误代码及错误提示枚举类:

public enum EnumSystemCode {SUCC(2000, "SUCC"),ERROR_USER_NOT_EXIST(4001008, "用户不存在"),ERROR_TOKEN_TIMEOUT(4001010, "token失效"),ERROR_TOKEN(4001011, "token不正确"),   COMMON(0, "错误");@Getterprivate final int code;@Getterprivate final String conent;EnumSystemCode(int code, String content) {this.code = code;this.conent = content;}public static EnumSystemCode findByCode(int code) {for (EnumSystemCode sCode : EnumSystemCode.values()) {if (sCode.getCode() == code) {return sCode;}}return null;}}

2:编写检验失败抛出的CommonException类:

public class CommonException extends RuntimeException {private static final long serialVersionUID = 1L;@Getterprivate int code;@Getterprivate EnumSystemCode systemCode;public CommonException(int code, String msg) {super(msg);this.code = code;this.systemCode = EnumSystemCode.findByCode(code);}public CommonException(EnumSystemCode systemCode) {super(systemCode.getConent());this.code = systemCode.getCode();this.systemCode = systemCode;}public CommonException(EnumSystemCode systemCode, String msg) {super(msg);this.code = systemCode.getCode();this.systemCode = systemCode;}public CommonException(String msg) {this(EnumSystemCode.COMMON.getCode(), msg);}public static CommonException getInstance(String msg, Object... args) {for (Object object : args) {msg = msg.replaceFirst("\\{\\}", object.toString());}return new CommonException(msg);}public static CommonException getInstance(String msg) {return new CommonException(msg);}}

3.业务判断时,根据不同情况提示错误信息:

if (code == EnumSystemCode.SUCC.getCode()) {//校验成功
} else if (code == EnumSystemCode.ERROR_USER_NOT_EXIST.getCode()) {logger.info("用户不存在 , userId:{}", userId);throw new CommonException(code, EnumSystemCode.ERROR_USER_NOT_EXIST.getConent());
} else if (code == EnumSystemCode.ERROR_TOKEN_TIMEOUT.getCode()) {logger.info("token失效 , userId:{}, token:{}", userId, token);throw new CommonException(code, EnumSystemCode.ERROR_TOKEN_TIMEOUT.getConent());
} else if (code == EnumSystemCode.ERROR_TOKEN.getCode()) {logger.info("token不正确 , userId:{}, token:{}", userId, token);throw new CommonException(code, EnumSystemCode.ERROR_TOKEN.getConent());
}

4.抛出异常后,异常拦截器拦截:

@ControllerAdvice("com.***.web.resource")
public class ResponseAdvice implements ResponseBodyAdvice<Object> {@Overridepublic boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {return true;}@Overridepublic Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType,Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest,ServerHttpResponse serverHttpResponse) {ServletServerHttpResponse response = (ServletServerHttpResponse) serverHttpResponse;    return ApiResponse.builder().status(response.getServletResponse().getStatus()).msg("OK").data(o).build();}@ExceptionHandler(CommonException.class)@ResponseBodypublic ApiResponse<?> handleControllerException(HttpServletRequest request, CommonException e) {return ApiResponse.builder().status(e.getCode()).msg(e.getMessage()).build();}@ExceptionHandler(Exception.class)@ResponseBodypublic ApiResponse<?> handleControllerException(HttpServletRequest request, Throwable e) {HttpStatus status = getStatus(request);return ApiResponse.builder().status(status.value()).msg(e.getMessage()).build();}private HttpStatus getStatus(HttpServletRequest request) {Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");if (statusCode == null) {return HttpStatus.INTERNAL_SERVER_ERROR;}return HttpStatus.valueOf(statusCode);}
}

通过上述配置,我们便实现了一旦校验失败,程序中止执行,立刻返回错误代码的效果。

更多推荐

妙用CommonException

本文发布于:2024-02-13 09:33:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1758249.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:妙用   CommonException

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!