Reputation: 305
My application is supposed to return a custom HTTP status code when there is a business exception.
I'm trying to implement the HTTP status as 999 in case of a business exception but could not find a way to implement it in rest controller advice.
I want to return HTTP status 999 in case of a business exception. Please guide me on how to implement it.
@Import({ ErrorCodeUtil.class })
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
@Autowired
private ErrorCodeUtil errorCodeUtil;
@ExceptionHandler(BusinessException.class)
@ResponseStatus(// Return 999 here)
@ResponseBody
public ErrorResult handleException(BusinessException e) {
String msg = e.getMessage();
log.error(msg, e);
return new ErrorResult(e.getErrorCode(), msg);
}
Upvotes: 0
Views: 3450
Reputation: 1590
According to the standard, there are only five classes of Http Status code from 1xx to 5xx. Check this link.
What you can do is in your controller advice, define the return type with status code property.
For example:
ErrorResult errorResult = new ErrorResult();
errorResult.setStatusCode(900);
errorResult.setMessage(e.getMessage());
You can use @ResponseStatus(code = HttpStatus.BAD_GATEWAY)
instead. Now, the method looks like:
@ExceptionHandler(BusinessException.class)
@ResponseStatus(code = HttpStatus.BAD_GATEWAY)
@ResponseBody
public ErrorResult handleException(BusinessException e) {
ErrorResult errorResult = new ErrorResult();
errorResult.setStatusCode(e.getStatusCode()); //set status code 900 when throwing exception or use errorResult.setStatusCode(900);
errorResult.setMessage(e.getMessage());
}
Upvotes: 1