java 捕获特定异常_应用程序捕获特定异常后执行Spring ExceptionHandler

我在 Spring 天遇到异常处理问题 .

我有@Controller调用@Service,我有一个单独的ControllerAdvice .

该服务有两种方法,methodA和methodB . MethodB是发生异常的地方 . 以特定形式捕获后,例如 DuplicateKeyException 父类再次捕获它 . 如果我使父母不那么笼统而不仅仅是 grab Exception ,例如只 grab InterruptedException , ExecutionException 控制器建议选择错误并返回错误响应 .

有没有一种规范的方法来捕获这个特定的异常 DuplicateKeyException 并继续处理,好像什么也没发生过,并在没有触发ControllerAdvice的情况下将响应返回给客户端?

控制器建议

@ControllerAdvice

public class CustomExceptionHandler extends ResponseEntityExceptionHandler {

@ExceptionHandler(value = Exception.class)

public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {

//Do some error processing and return a view for the client

return mav;

}

}

控制器

@Controller

public ControllerClass(){

@RequestMapping("/test", method = RequestMethod.POST, produces = "application/json")

@ResponseBody

public ResponseEntity getCustomerData(omitted) throws SQLException, JsonProcessingException {

CustomerData customerData = serviceCalss.methodA();

//futher processing and return valid return type

return new ResponseEntity();

}

}

服务

public class ServiceClass{

public CustomerData methodA(){

try {

@SuppressWarnings("unchecked")

Collection someCollection = (Collection) result.get(); // this line possibly throws InterruptedException, ExecutionException

//do some stuff then call methodB

methodB();

}catch (Exception e) {

logger.error("Error getting aggregated results", e);

//Custom Error processing

}

}

}

public void methodB() {

try {

persistence.insertNewData(data);

}catch(DuplicateKeyException dke) {

logger.warn("Unable to create blah, Specific Error Message{}", dke);

}catch (SQLException e) {

Error error = new Error();

error.developerinfo = e.toString();

error.text = e.getMessage();

throw new CustomEXceptionWhichExtendsException("custom error message not related to this example, error);

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值