I've a SOAP web service built in Java.
If my method runs into an exception I want to return a "HTTP CODE 500".
Is it possible? If yes how?
(Web service is running on Tomcat 6)
maybe you should simply throw a qualified Exception yourself which then will be sent back to the client as a soap fault. W3C tells us this:
In case of a SOAP error while processing the request, the SOAP HTTP server MUST issue an HTTP 500 "Internal Server Error" response and include a SOAP message in the response containing a SOAP Fault element (see section 4.4) indicating the SOAP processing error. http://www.w3.org/TR/2000/NOTE-SOAP-20000508/
Messing with http response codes could be dangerous as some other client might expect a different response. In your case you'd be lucky because you want exactly the the behaviour as specified by W3C. So throw an Exception ;)
How to do that? Take a look here: How to throw a custom fault on a JAX-WS web service?
Greetings
Bastian
Since the JAX-WS is based on servlets, you can do it. You can try the next:
@WebService
public class Calculator {
@Resource
private WebServiceContext ctx;
public int division (int a, int b) {
try {
return a / b;
} catch (ArithmeticException e) {
sendError(500, "Service unavailable for you.");
return -1; // never send
}
}
private void sendError(int status, String msg) {
try {
MessageContext msgCtx = ctx.getMessageContext();
HttpServletResponse response =
(HttpServletResponse) msgCtx.get(MessageContext.SERVLET_RESPONSE);
response.sendError(status, msg);
} catch (IOException e) {
// Never happens or yes?
}
}
}
However, I prefer to use JAX-RS to do something similar.
@PUT
@Path("test")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response update( //
@FormParam("id") int id,
@FormParam("fname") String fname,
@FormParam("lname") String lname
) {
try {
// do something
return Response.ok("Successfully updated",
MediaType.TEXT_PLAIN_TYPE).build();
} catch (Exception e) {
LOG.error("An error occurred", e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity("An error occurred")
.type(MediaType.TEXT_PLAIN_TYPE).build();
}
}