美文网首页
jesery自定义异常,其他框架也可参考

jesery自定义异常,其他框架也可参考

作者: 后来丶_a24d | 来源:发表于2020-09-22 17:07 被阅读0次

自定义异常类

  • exception类数据结构填充由枚举类定义
  • 接口 ErrorDef
public interface ErrorDef {
    String getErrorCode();
    String getMsg();
}
  • BadRequestException
public class BadRequestException extends RuntimeException implements ErrorDef{
    // 不同项目可以自个实现, 故此做拓展
    private final ErrorDef errorCode;

    public BadRequestException(ErrorCodeEnum errorCode) {
        super(errorCode.getMsg());
        this.errorCode = errorCode;
    }

    @Override
    public String getErrorCode() {
        return errorCode.getErrorCode();
    }

    @Override
    public String getMsg() {
        return errorCode.getMsg();
    }
}
  • ErrorCodeEnum
public enum ErrorCodeEnum implements ErrorDef {
    TEST("600", "test"),
    ;

    private final String errorCode;
    private final String msg;

    ErrorCodeEnum(String errorCode, String msg) {
        this.errorCode = errorCode;
        this.msg = msg;
    }

    public static ErrorCodeEnum getErrorCodeEnum(String errorCode) {
        return StringUtils.isEmpty(errorCode) ? null :
                Arrays.stream(ErrorCodeEnum.values())
                        .filter(errorCodeEnum -> errorCode.equals(errorCodeEnum.errorCode))
                        .findAny().orElse(null);
    }

    @Override
    public String getErrorCode() {
        return errorCode;
    }

    @Override
    public String getMsg() {
        return msg;
    }
}

定义ExceptionMapper

  • ExceptionMapper, 定义抽象类是希望可拓展status,errorDef这两块。后续有需求status,errorDef改动直接继承就好
public abstract class ExceptionMapper {

    protected Response buildResponse(Response.Status status, ErrorDef errorDef) {
        var builder = Response.status(status).entity(map(errorDef));

        return builder.build();
    }

    private Object map(ErrorDef errorDef) {
        Map<String, String> map = new HashMap<>();
        map.put("code", errorDef.getErrorCode());
        map.put("message", errorDef.getMsg());
        return map;
    }
}
  • BadRequestExceptionMapper
@Provider
public class BadRequestExceptionMapper extends ExceptionMapper
        implements ExceptionMapper<BadRequestException> {

    @Override
    public Response toResponse(BadRequestException exception) {
        return buildResponse(BAD_REQUEST, exception);
    }
}

使用

ErrorCodeEnum errorCodeEnum = ErrorCodeEnum.getErrorCodeEnum(errorCode);
if(errorCodeEnum != null) {
    throw new BadRequestException(errorCodeEnum);
 }

相关文章

网友评论

      本文标题:jesery自定义异常,其他框架也可参考

      本文链接:https://www.haomeiwen.com/subject/obnwyktx.html