我有一个休息的网络服务。如果引发任何异常,Web服务将返回http 500错误。但是我不想发送带有异常堆栈跟踪的错误响应。我只想发送错误代码和错误消息。我没有实现。我该怎么办?
我已经尝试过@ControllerAdvice和@ExceptionHandler批注,但是我不能。当我使用@ResponseStatus批注时,请始终发送静态的“ reason”值。如何设置该值?感谢您的帮助。
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"
}
}
}
答案 0 :(得分:1)
有许多可能的解决方案,我很确定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();
}
}