我有一个休息网络服务。如果抛出任何异常,Web 服务将返回 http 500 错误。但我不想发送带有异常堆栈跟踪的错误响应。我只想发送错误代码和错误消息。我没有实现这一目标。我怎样才能做到这一点?
我已经尝试过 @ControllerAdvice 和 @ExceptionHandler 注释,但我不能。当我使用 @ResponseStatus 注释时,始终发送静态“原因”值。我该如何设置这个值?感谢您的帮助。
public class SendMessageController{
private Logger log = LogManager.getLogger(getClass());
@Autowired
private QueueService queueService;
@RequestMapping(value="/message/check", method = RequestMethod.POST, headers={ "content-type=application/json"})
public @ResponseBody
ApiResponse sendMessage(@RequestBody String requestMessage) throws Exception {
try {
return new ApiResponse(queueService.processRequestForJSONString(requestMessage);
} catch (Exception e) {
throw new GenericException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
//throw e;
}
}
@ResponseStatus(value=HttpStatus.INTERNAL_SERVER_ERROR, reason="Exception Message")
public class GenericException extends Exception {
public HttpStatus httpCode;
public String errorMessage;
public GenericException(HttpStatus httpCode, String errorMessage){
this.httpCode = httpCode;
this.errorMessage = errorMessage;
//I can't set "reason"
}
}
}
最佳答案
有很多可能的解决方案,我很确定 ErrorHandler 是更好的方法。
@GetMapping(value="/{empId}", produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<EmployeeInfoItem> getEmployeeInfo(@PathVariable("empId") Integer empId) {
try {
...
} catch (Exception e) {
logger.error( e.getMessage() );
return ResponseEntity.status(HttpStatus.FAILED_DEPENDENCY).build();
}
}
关于java - Rest - 如何在没有堆栈跟踪的情况下发送 Http 错误响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55763100/