Guest User

Untitled

a guest
Nov 21st, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.60 KB | None | 0 0
  1. public Entity getEntityWithOptions(@PathParam("id") String id, @QueryParam("option") String optValue) {
  2. if (optValue != null) {
  3. // Option is an enum
  4. try {
  5. Option option = Option.valueOf(optValue);
  6. } catch (IllegalArgumentException e) {
  7. throw new BadRequestException(e.getMessage());
  8. }
  9. return new Entity(option);
  10. }
  11. return new Entity();
  12. }
  13.  
  14. public class CustomException extends RuntimeException {
  15. public CustomException(Throwable throwable) {
  16. super(throwable);
  17. }
  18.  
  19. public CustomException(String string, Throwable throwable) {
  20. super(string, throwable);
  21. }
  22.  
  23. public CustomException(String string) {
  24. super(string);
  25. }
  26.  
  27. public CustomException() {
  28. super();
  29. }
  30. }
  31.  
  32. @Provider
  33. public class CustomExceptionMapper implements ExceptionMapper<CustomException> {
  34. private static Logger logger = Logger.getLogger(CustomExceptionMapper.class.getName());
  35. /**
  36. * This constructor is invoked when exception is thrown, after
  37. * resource-method has been invoked. Using @provider.
  38. */
  39. public CustomExceptionMapper() {
  40. super();
  41. }
  42.  
  43. /**
  44. * When exception is thrown by the jersey container.This method is invoked
  45. */
  46. public Response toResponse(CustomException ex) {
  47. logger.log(Level.SEVERE, ex.getMessage(), ex);
  48. Response.ResponseBuilder resp = Response.status(Response.Status.BAD_REQUEST)
  49. .entity(ex.getMessage());
  50.  
  51. return resp.build();
  52. }
  53. }
  54.  
  55. public Entity getEntityWithOptions(@PathParam("id") String id,
  56. @QueryParam("option") String optValue)
  57. throws CustomException {
  58. if (optValue != null) {
  59. // Option is an enum
  60. try {
  61. Option option = Option.valueOf(optValue);
  62. } catch (IllegalArgumentException e) {
  63. throw new CustomException(e.getMessage(),e);
  64. }
  65. return new Entity(option);
  66. }
  67. return new Entity();
  68. }
  69.  
  70. Response.ResponseBuilder resp_builder=Response.status(Response.Status.BAD_REQUEST);
  71. resp_builder.entity(e.getMessage());//message you need as the body
  72. throw new WebApplicationException(resp_builder.build());
  73.  
  74. public class CustomBadReq extends WebApplicationException {
  75. public CustomBadReq(String message) {
  76. super(Response.status(Response.Status.BAD_REQUEST)
  77. .entity(message).type(MediaType.TEXT_PLAIN).build());
  78. }
  79. }
  80.  
  81. String msg = e.getMessage();
  82. throw new BadRequestException(Response.status(BAD_REQUEST)
  83. .entity(msg).build());
Add Comment
Please, Sign In to add comment