Reputation: 196
I have an rest web service. If any exception thrown, web service return http 500 error. But I don't want to send this error response with exception stack trace. I just want to send with error code and error message. I didn't achieve this. How can I do this?
I already tried @ControllerAdvice and @ExceptionHandler annotations but I couldn't. When I used @ResponseStatus annotation, always send static "reason" value. How can I set this value? Thank for your help.
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"
}
}
}
Upvotes: 0
Views: 1685
Reputation: 11551
There are many possible solutions and I'm pretty sure an ErrorHandler is a much better way to go.
@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();
}
}
Upvotes: 1