java.lang.IllegalStateException:提交响应后无法调用 sendError()
如上所述,我在响应 .sendError() 方法行中收到错误。我在网上搜索了4天。但我无法找出问题所在。这个问题的原因可能是什么?
我有一个自定义异常类。
在下面的代码中,catch 块成功捕获了我的自定义异常。但是当我尝试将其发送到客户端时,它返回上面提到的异常。
我已经尝试过了
解决方案1 – 控制器级别@ExceptionHandler
解决方案 2 – HandlerExceptionResolver
解决方案 3 – @ControllerAdvice
解决方案 4 – ResponseStatusException
解决上述问题的方法。但对我不起作用:(
我已将错误代码和错误消息添加到响应正文中。然后我就可以成功得到错误了。但这不是我想要的方式。
@RequestMapping(value="/getMemberID/", method=RequestMethod.POST ,headers ="Accept=application/json")
public ResponseMemberID getMemberID(@RequestBody RequestMemberID request,HttpServletResponse response, @Context HttpServletRequest _request ) throws Exception {
Member_info memberinfo = new Member_info();
ResponseMemberID _response =new ResponseMemberID();
try {
memberinfo = memberinfoservice.getMemberID(request.getPin(),request.getMsisdn());
_response.setMember_id(memberinfo.getMember_id());
}catch(MemberNotFoundException exp) {
response.sendError(exp.getErrorCode(), exp.getErrorMessage());
}
return _response;
}
我需要使用上面的 sendError() 方法获取错误代码和错误消息作为 JSON 响应。异常成功到达 catch 块。
这里,
1)您需要为自定义异常添加错误处理程序
2)错误处理程序将抛出异常
一些有用的链接:处理Spring Hibernate SQL错误的推荐方法 https://stackoverflow.com/questions/50846360/recommended-way-of-dealing-with-spring-hibernate-sql-errors/50850529#50850529
Spring有没有更简单的异常处理技术? https://stackoverflow.com/questions/51008530/is-there-a-simpler-exception-handling-technique-for-spring/51008726#51008726
注意:此方法已经过测试,我正在我的应用程序中使用它。
@RestControllerAdvice
@RequestMapping(produces = "application/json")
public class DefaultExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(MemberNotFoundException .class)
@ResponseStatus(value = HttpStatus.CONFLICT)
public Map<String, String> handleConstraintViolationException(ConstraintViolationException ex) {
Map<String, String> response = new HashMap);
// set your response
return new ResponseEntity<>(response, ex.getStatus());
}
}
From, getMemberID
, 消除try
and catch
block.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)