4

I am developing REST services using camel REST-DSL [in camel documentation] component.I am successful in sending JSON request for happy path and get the response on the same using (Rest-DSL and camel servlet) combination. Now as we move forward the client may sent Rest Service request with not enough values or invalid valid request ,now I am looking for ways to send 400 status code as a response from REST DSL when request is not valid.

Please advise on the way to achieve this.

Naveen Raj
  • 801
  • 11
  • 26
Leo Prince
  • 940
  • 2
  • 14
  • 33
  • You would like to make some processing and then based on that you need to send the not valid response? if so then response form Pierre-Alban would work. Or Do you need to send the invalid response when a specific error scenario happens? – Naveen Raj Oct 30 '14 at 12:39
  • correct Naveen,so I will validate the input and then if validation fails I need to sent Response of 400 Status Code. – Leo Prince Oct 30 '14 at 17:46

2 Answers2

8

I am assuming you are doing your validation in a custom processor or something similiar. If you want to send your an HTTP Error code just add the header Exchange.HTTP_RESPONSE_CODE.

For example : exchange.getIn().setHeader(Exchange.HTTP_RESPONSE_CODE, 400);

The behaviour may depend of the engine you use. As documentation says it should work with servlet engine :

  • Thanks , Worked Perfect ! One observation is we need to avoid any exception that may come underway as if I get exception ,Camel Servlet sends 500 Status Codes -saying Internal server error. – Leo Prince Oct 30 '14 at 17:48
  • 2
    I think you could use the exception strategy and alter the headers for other status codes and response if required. – Naveen Raj Oct 31 '14 at 10:17
  • beware, wrapping `400` in `constant(400)` causes this to not work, using the REST component at least – b15 Jun 12 '20 at 14:14
7

As suggested by Pierre-Alban you may validate the payload in processor or service class and set the correct response code and message in processor.

Another way is to throw an exception from validator method and let the route builder handle that exception. Something like this:

onException(ValidationException.class)
    .handled(true)      
    .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(400))
    .setHeader(Exchange.CONTENT_TYPE, constant("text/plain"))
    .setBody(exceptionMessage());
thokuest
  • 5,800
  • 24
  • 36
Amarjeet
  • 113
  • 2
  • 9