I have REST endpoint which has injected services.
@Singleton
@Path("/v1/service")
public class MyService {
@Inject
private TokenService tokenService;
@Inject
private InfoService infoService;
@GET
@Path("/info")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public InfoResponse getInfo(@HeaderParam("Authorization") String token){
tokenService.validateToken(token);
List<String> info = infoService.getInfo();
// processing info code, throwing WebServiceException if something wrong
return new InfoResponse(info);
}
}
Some of them validates data, for example token, and throws RestServiceException exception if it is incorrect. Exceptions are processed by ExceptionMapper so appropriate Response is returned. Other services return/process information.
My custom exception class with additional fields:
public class RestServiceException extends WebServiceException {
public Integer httpStatus;
public String message;
}
Example service method:
public User getUser(Long userId){
User user = userMapper.getUser(userId);
if (user == null){
String msg = "Invalid user: " + userId;
logger.debug(msg);
throw new RestServiceException(HttpStatus.SC_NOT_FOUND, InternalStatus.INVALID_USER, msg);
}
return user;
}
Is good practice to throw RestServiceException in injected services? How to design code to facilitate testing? Where to put validation methods - service or static class?