you can directly use WebApplicationException from jax-rs to throw the exception
For Example:
if(products==null){
throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).entity("products does not exist.").build());
}
If you have your custom exception then you can extends WebApplicationException
public class BusinessException extends WebApplicationException {
public BusinessException(Response.Status status, String message) {
super(Response.status(status)
.entity(message).type(MediaType.TEXT_PLAIN).build());
}
}
throw from your code
if(products==null){
throw new BusinessException(Response.Status.NOT_FOUND,"products does not exist.");
}
you can use error response object to display clean way
public class ErrorResponse {
private int status;
private String message;
ErrorResponse(int status,String message){
this.status = status;
this.message = message;
}
//setters and getters here
}
create ErrorResponse object while throwing the exception
public class BusinessException extends WebApplicationException {
public BusinessException(Response.Status status, String message) {
super(Response.status(status)
.entity(new ErrorResponse(status.getStatusCode(),message)).type(MediaType.APPLICATION_JSON).build());
}
}
In postman it will display like below
{
status:404,
message:"products does not exist."
}