标签:规则 compareto close ali mapping 安全性 定义 adf fail
Exception主要分为两种:Runtime Exception、Checked(Compile) Exception。
常见的Runtime Exception,有:NullPointerException、ArithmeticException...
常见的Checked(Compile) Exception,有:IOException、FileNotFoundException...
所谓Checked Exception就是在编译期间,你必须对某条、或多条语句进行异常处理,如: try...catch...、throws语句。
下面介绍下Checked Exception的优缺点:
Error主要表示一些虚拟机内部错误,如:动态链接失败。
public class ExceptionTest { public static void readFile(){ try(BufferedReader bufferedReader = new BufferedReader(new FileReader("justForTest.txt"))) { System.out.println(bufferedReader.readLine()); } catch (IOException e) { e.printStackTrace(); } } } @Test public void readFileTest(){ ExceptionTest.readFile(); // Just for test. }
@Getter public class ServiceException extends RuntimeException { private HttpStatus status; private ResultCode resultCode; private Object errorData; private ServiceException(HttpStatus status, ResultCode resultCode, Object errorData){ this.status = status; this.resultCode = resultCode; this.errorData = errorData; } public static ServiceException badRequest(ResultCode resultCode, Object errorData){ return new ServiceException(HttpStatus.BAD_REQUEST, resultCode, errorData); } } @Getter public enum ResultCode { // errorCode SUCCESS(0, "SUCCESS"), INVALID_PARAMETER(600, "invalid parameter"); private final int errorCode; private final String errorData; ResultCode(int errorCode, String errorData){ this.errorCode = errorCode; this.errorData = errorData; } } @ControllerAdvice public class GlobalErrorHandler { @ExceptionHandler(ServiceException.class) public ResponseEntity<ErrorResponse> handleServiceException(ServiceException ex){ return ResponseEntity .status(ex.getStatus()) .body(ErrorResponse.failed(ex.getResultCode(), ex.getErrorData())); } } @ApiModel @Getter public class ErrorResponse<T> implements Serializable { private static final long serialVersionUID = -2254339918462802230L; private final int errorCode; private final String errorMsg; private final T errorData; private ErrorResponse(ResultCode resultCode, T errorData) { this.errorCode = resultCode.getErrorCode(); this.errorMsg = resultCode.getErrorData(); this.errorData = errorData; } public static <T> ErrorResponse<T> failed(ResultCode resultCode, T data){ return new ErrorResponse(resultCode, data); } } @RestController public class OrderController { @GetMapping(value = "/v1/orders/{order_id}"/*, produces = {"application/toString", "application/json"}*/) public Order getOrder(@PathVariable("order_id") @NotBlank String orderId){ Order order = new Order(); BigDecimal total = new BigDecimal(-1.00, new MathContext(2, RoundingMode.HALF_UP)); if (total.compareTo(BigDecimal.ZERO) <= 0){ throw ServiceException.badRequest(ResultCode.INVALID_PARAMETER, "Total is less than zero!"); } order.setOrderId(orderId); order.setTotal(total); return order; } }
标签:规则 compareto close ali mapping 安全性 定义 adf fail
原文地址:https://www.cnblogs.com/YaoFrankie/p/11440626.html