Exception handling in JAX-RS RESTEasy with ExceptionMapper

JAX-RS RESTEasy has very good support for all kind of application activities which can be customized to desired level. One of such capability is Exception handling. To build custom exception handlers, JAX-RS providesExceptionMapper interface.

ExceptionMapper is a contract for a provider that maps Java exceptions to Response object. An implementation of this interface must be annotated with Provider to work correctly.

How to build custom exception handler

A sample implementation provider class looks like this:

packagecom.howtodoinjava.exception;
 
importjavax.ws.rs.core.Response;
importjavax.ws.rs.core.Response.Status;
importjavax.ws.rs.ext.ExceptionMapper;
importjavax.ws.rs.ext.Provider;
 
@Provider
publicclass MyApplicationExceptionHandler implementsExceptionMapper<MyApplicationException> 
{
    @Override
    publicResponse toResponse(MyApplicationException exception) 
    {
        returnResponse.status(Status.BAD_REQUEST).entity(exception.getMessage()).build();  
    }
}


Where the MyApplicationException.java is written as:

packagecom.howtodoinjava.exception;
 
importjava.io.Serializable;
 
publicclass MyApplicationException extendsException implementsSerializable
{
    privatestatic final long serialVersionUID = 1L;
    publicMyApplicationException() {
        super();
    }
    publicMyApplicationException(String msg)   {
        super(msg);
    }
    publicMyApplicationException(String msg, Exception e)  {
        super(msg, e);
    }
}

Demo usage of ExceptionMapper

To test the ExceptionMapper implementation, I have written following REST API.

packagecom.howtodoinjava.rest;
 
importjavax.ws.rs.GET;
importjavax.ws.rs.Path;
importjavax.ws.rs.PathParam;
importjavax.ws.rs.core.Response;
 
importorg.jboss.resteasy.spi.validation.ValidateRequest;
 
importcom.howtodoinjava.exception.MyApplicationException;
 
@Path("/rest")
publicclass UserService 
{
    @Path("/users/{id}")
    @GET
    @ValidateRequest
    publicResponse getUserBId  ( @PathParam("id") String id ) throwsMyApplicationException
    {
        //validate mandatory field
        if(id == null)
        {
            thrownew MyApplicationException("id is not present in request !!");
        }
        //Validate proper format
        try
        {
            Integer.parseInt(id);
        }
        catch(NumberFormatException e)
        {
            thrownew MyApplicationException("id is not a number !!");
        }
        //Process the request
        returnResponse.ok().entity("User with ID " + id + " found !!").build();
    }
}

Above API accepts the user id parameter in Integer format. If we pass the id in some other format which can not be parsed to Integer, it will throw MyApplicationException. Our exception mapper should be able to handle this.

1) Valid request http://localhost:8080/RESTEasyExceptionMapperDemo/rest/users/1

Valid request to REST API

Valid request to REST API

2) Invalid request http://localhost:8080/RESTEasyExceptionMapperDemo/rest/users/abc

Invalid request to REST API

Invalid request to REST API

To download the sourcecode of above application, follow below given link.

Sourcecode Download

Happy Learning !!


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值