方案1: 场景: 接口异常统一处理
方案2: 场景: 常见异常统一处理, 避免try {}catch(){} 直接处理, 使代码更加清晰, 适用于几乎所有场景
方案1:
@Data @NoArgsConstructor @AllArgsConstructor @Document("promotion_record") public class PromotionRecordDO { private String _id; private String channel; //最终的推广标签 cn = cnId +"_"+promoterId @NotBlank(message = "推广渠道 id can,t be blank") private String cnId; //推广渠道channel id 123 @NotBlank(message = "推广渠道 cnName can,t be blank") private String cnName; //推广渠道 推广渠道channel name wechat,Tiktok @NotBlank(message = "推广人 promoter id can,t be blank") private String promoterId; //推广人 sea @NotBlank(message = "推广人 promoterName can,t be blank") private String promoterName; //推广人 sea private String behavior; //行为 pv @NotBlank(message = "描述 desc can,t be blank") private String desc;//描述 :跨境智慧帮抖音渠道推广 private String opId;//操作者id private String opName;//操作者name }
@ApiOperation(value = "/promotion/oprecord",notes = "op record promotion event")
@PostMapping("oprecord")
public JSONObject receive(@RequestBody @Validated PromotionRecordDO promotion) {
return promotionRecordHandler.opRecord(promotion);
}
@RestControllerAdvice @Component @Slf4j public class ExceptionAdvice { /** * controller 配和@Validated eg:add(@RequestBody @Validated CategoryDO category) * @param exception * @return */ @ExceptionHandler(MethodArgumentNotValidException.class) public JSONObject validExceptionHandler(MethodArgumentNotValidException exception) { List<ObjectError> allErrors = exception.getBindingResult().getAllErrors(); List<String> collect = allErrors.stream().map(e -> e.getDefaultMessage() + "\n").collect(Collectors.toList()); return ResponseUtil.getResult(ResponseCode.VALIDATION_ERROR.getCode(), ResponseCode.VALIDATION_ERROR.getMessage(), collect); } @Order(100) //last do if not catch exception @ExceptionHandler(Exception.class) public JSONObject process(Exception e) { log.error("exception:", e); return ResponseUtil.getResult(ResponseCode.SYSTEM_ERROR.getCode(), ResponseCode.SYSTEM_ERROR.getMessage(), e.getMessage()); } }
方案2:
1.依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
2. 避免直接切方法--> 这使用一个exceptionHandlerUtils, 然后切片切utils
exceptionHandlerUtils:
@Slf4j @Component public class ExceptionHandlingUtils { public void throwDAOException(Exception e){ e.printStackTrace(); log.error("Failed to operate booking into Mysql, caused by: {}",e.getMessage(),e); throw new DAOException(e.getMessage(),e); } public void printEmailException(Exception e,String subject, String to) { e.printStackTrace(); log.error("***EmailException,Failed to send email {} to {}***, caused by: {}",subject,to,e.getMessage()); } public void throwJSONConvertException(Exception e) { e.printStackTrace(); log.error("Exception encountered at read json tree, caused by: {}",e.getMessage(),e); throw new JSONConvertException(e.getMessage(),e); } }
3. AOP 切片:
ExceptionHandlingAspect
@Aspect @Configuration @Slf4j public class ExceptionHandlingAspect { @Value("${mail.common.from}") private String from; @Value("${mail.common.to}") private String to; @Autowired private MesgHelper mesgHelper; /** * @param joinPoint * @param ex ,获取的异常 */ @AfterThrowing(pointcut = "execution(* com.icil.elsa.auo.common.util..*(..))", throwing = "ex") public void afterThrowingCommon(JoinPoint joinPoint, Throwable ex){ log.error("Exception was detected, caused by {}",ex.getMessage()); if(ex instanceof DAOException){ commonProcess(ex); } else if(ex instanceof RestClientException){ commonProcess(ex); } else if(ex instanceof ConnectionException){ commonProcess(ex); } } private void commonProcess(Throwable ex) { log.error("Processing exception with name {}",ex.getClass().getSimpleName()); Object[] paras = {DateUtils.getBeiJingDateLoc()}; String subject = mesgHelper.getMessage("exception.handling.common.subject", paras, null); String exSimpleName = ex.getClass().getSimpleName(); String body = ex.getMessage(); Object[] params = { exSimpleName, body}; String content = mesgHelper.getMessage("exception.handling.common.content", params, null); MailUtils.sendMail(to,from,subject,content); } }
4.使用:
try { //doing something }catch(Exception e ){ exceptionHandlingUtils.throwDAOException(e); }