Java – how to set 40x errors using custom messages on jax-rs exceptions?

I am working on Web services on Jax - rs Now I'm looking for a way to catch some exceptions to send a custom message of 40x error to the user

I have a web service and an exception mapper

This is my web service:

@Path( value = "/test/")
public interface ServiceTest {

    @Path(value = "{rrf}")
    @GET
    @Produces(MediaType.TEXT_XML)
    public ObjectDTO getDealer(@PathParam("rrf") String rrf){
        ObjectDTO objectDTO = new ObjectDTO();
        if( verifyRRFSintax(rrf) ) {
            //Get the objet,this part works fine
        } else {
            throw new IllegalArgumentException("Custom message");
        } 
        return dwsDTO;
    }

    private boolean verifyRRFSintax(String rrf) {
        return rrf.matches("[0-9]{8}");
    }
}

This is my exceptionmapper

@Provider
@Produces(MediaType.TEXT_XML)
public class IllegalArgumentExceptionMapper 
    implements ExceptionMapper<IllegalArgumentException> {

    @Override
    public Response toResponse(IllegalArgumentException e) {
        return Response.status(Response.Status.BAD_REQUEST).build();
    }
}

This is it in application context Registration method in XML file

<bean id="serviceTest" class="ServiceTest"/>

<jaxrs:server id="Server" address="/ws">
    <jaxrs:serviceBeans>
        <ref bean="serviceTest"/>
    </jaxrs:serviceBeans>
    <jaxrs:providers>
        <bean id="rffErrorException" class="IllegalArgumentExceptionMapper"/>
    </jaxrs:providers>
</jaxrs:server>

When I debug, the illegalargumentexceptionmapper catches and throws an exception, but I can't see the message on the yellow web page displayed in the browser I always have one

How can I display this custom message on the browser? Why, even if I change the type of response status (not_found, bad_request, forward), the yellow page is always the same?

PD: on the console, I have a message "out. Handlemessage", which is printed when mapper catches an exception

thank you.

Solution

throw new WebApplicationException(Response.status(Status.NOT_FOUND)// Or another Status
throw new WebApplicationException(Response.status(Status.NOT_FOUND)// Or another Status
                .entity("Error Message").build());
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>