RESTEasy ExceptionMapper – 异常处理示例

RESTEasy ExceptionMapper – 异常处理示例

原文: https://howtodoinjava.com/resteasy/exception-handling-in-jax-rs-resteasy-with-exceptionmapper/

学习使用 resteasy ExceptionMapper接口实现创建和处理自定义异常ExceptionMapper是供应器的契约,该供应器将 Java 异常映射到Response对象。

必须使用@Provider注解ExceptionMapper接口的实现才能正常工作。

1. Resteasy ExceptionMapper - 自定义异常处理器

ExceptionMapper的示例实现供应器类如下所示:

package com.howtodoinjava.exception;

import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

@Provider
public class MyApplicationExceptionHandler implements ExceptionMapper<MyApplicationException> 
{
	@Override
	public Response toResponse(MyApplicationException exception) 
	{
		return Response.status(Status.BAD_REQUEST).entity(exception.getMessage()).build();	
	}
}

自定义异常类MyApplicationException.java的编写方式为:

package com.howtodoinjava.exception;

import java.io.Serializable;

public class MyApplicationException extends Exception implements Serializable
{
	private static final long serialVersionUID = 1L;

	public MyApplicationException()	{
		super();
	}
	public MyApplicationException(String msg)	{
		super(msg);
	}
	public MyApplicationException(String msg, Exception e)	{
		super(msg, e);
	}
}

2. Resteasy REST API

为了测试ExceptionMapper实现,我编写了以下 resteasy REST API。

package com.howtodoinjava.rest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

import org.jboss.resteasy.spi.validation.ValidateRequest;

import com.howtodoinjava.exception.MyApplicationException;

@Path("/rest")
public class UserService 
{
	@Path("/users/{id}")
	@GET
	@ValidateRequest
	public Response getUserBId	( @PathParam("id") String id ) throws MyApplicationException
	{
		//validate mandatory field
		if(id == null)
		{
			throw new MyApplicationException("id is not present in request !!");
		}
		//Validate proper format
		try
		{
			Integer.parseInt(id);
		}
		catch(NumberFormatException e)
		{
			throw new MyApplicationException("id is not a number !!");
		}
		//Process the request
		return Response.ok().entity("User with ID " + id + " found !!").build();
	}
}

3. RESTEasy ExceptionMapper演示

上面的 API 接受Integer格式的用户'id'参数。 如果我们以无法解析为Integer的其他格式传递 id,则会抛出MyApplicationException。 我们的异常映射器应该能够处理这个问题。

3.1 有效请求

在浏览器中访问http://localhost:8080/RESTEasyExceptionMapperDemo/rest/users/1

Valid request to REST API

REST API 的有效请求

3.2 无效请求 - 引发异常

在浏览器中访问http://localhost:8080/RESTEasyExceptionMapperDemo/rest/users/abc

Invalid request to REST API

REST API 的无效请求

要使用ExceptionMapper接口下载此 Resteasy 客户端异常处理示例的源代码,请遵循以下给定的链接。

源码下载

学习愉快!