我使用spring mvc,处理excpetion我使用全局异常处理程序
@ControllerAdvice
public class GlobalControllerExceptionHandler {
@ResponseStatus(value = HttpStatus.CONFLICT, reason = "Data integrity violation")
@ExceptionHandler({DataIntegrityViolationException.class})
public @ResponseBody AdminResponse handleConflict(DataIntegrityViolationException ex,HttpServletResponse httpServletResponse) {
AdminResponse error = new AdminResponse ();
httpServletResponse.setStatus(HttpStatus.CONFLICT.value());
error.setStatus(Status.FAILURE);
error.setErrorDescription(ex.getMessage());
return error;
}
据我所知,注释@ResponseStatus(value = HttpStatus.CONFLICT
会将休息状态代码更改为HttpStatus.CONFLICT
,但这不会发生。
当我创建虚拟异常并使用@ResponseStatus
注释此虚拟异常然后抛出此新异常时,GlobalControllerExceptionHandler
捕获并处理异常并更改响应状态代码。
如何更改响应状态代码而不创建新的Exception,我只需要捕获DataIntegrityViolationException
答案 0 :(得分:1)
你走两路。
<强> 1。使用@ResponseBody并返回自定义JSON字符串。
private final ActorSystem actorSystem;
private final ExecutionContext executionContext;
private final RgsDataServiceServices rgsDataServiceServices;
@Inject
public AutoGateJob(ActorSystem system, ExecutionContext context, RgsDataServiceServices rgsDataServiceServices) {
Logger.info("### create autojob");
this.actorSystem = system;
this.executionContext = context;
this.rgsDataServiceServices = rgsDataServiceServices
this.initialize();
}
<强> 2。使用ResponseEntity和异常
返回ResponseEntity。
@ExceptionHandler(value = { HttpClientErrorException.class, HTTPException.class })
public @ResponseBody String checkHTTPException(HttpServletRequest req, Exception exception,
HttpServletResponse resp) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
CommonExceptionModel model = new CommonExceptionModel();
model.setMessage("400 Bad Request");
model.setCode(HttpStatus.BAD_REQUEST.toString());
String commonExceptionString = mapper.writeValueAsString(model);
return commonExceptionString;
}