Reputation: 629
I have a rest controller in a spring boot service as follows:
Public ResponseEntity getDocContent(String id)
THis controller action produces MediaType.Octet_Stream
I am wondering what to return in case of non Http OK response when I really don’t have a byte array content but a String with error message. I would not want to produce an octet stream in error cases but an error JSon instead
I can have The service produce both octet stream and application/json but my confusion is around the return type of byte array in case of errors in which case I want to generate a Json and not a byte array
Please give me ideas on how to solve this
Upvotes: 2
Views: 2065
Reputation: 2509
Add a controllerAdvice
to handle the thrown exceptions in the RestContoller
.
@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler{
@ExceptionHandler(MyException.class)
@ResponseStatus(HttpStatus.CONFLICT) //Just an example code
public ResponseEntity<GeneralMessage> handleGacaException(MyException ex) {
LOGGER.error(ex.getMessage());
GeneralMessage errorMessage = new GeneralMessage(ex.getErrorCode().toString(), ex.getErrorMessage());
return ResponseEntity.status(HttpStatus.CONFLICT).body(errorMessage);
}
}
Than throw MyException
on the RestController.
Upvotes: 1