但是,将try-catch-finally块放在所有代码中并不是一个好习惯。 我们应该以这样一种方式设计/编码,如果发生任何不可恢复的错误,那么代码应该抛出该异常,并且应该有一个异常处理程序来捕获这些异常并提取错误详细信息,并对所有错误给出正确的错误响应错误详细信息。
RESTEasy提供了这样的ExceptionHandler机制,该机制简化了ExceptionHandling过程。
在这一部分中,我将向您展示如何使用RESTEasy的ExceptionHandlers处理异常。
步骤#1:创建应用程序特定的异常。
**
* ResourceNotFoundException.java
*
package com.sivalabs.resteasydemo;
public class ResourceNotFoundException extends RuntimeException
{
private static final long serialVersionUID = 1L;
public ResourceNotFoundException(String msg)
{
super(msg);
}
}
**
* ApplicationException.java
*
package com.sivalabs.resteasydemo;
import java.io.PrintWriter;
import java.io.StringWriter;
public class ApplicationException extends RuntimeException
{
private static final long serialVersionUID = 1L;
public ApplicationException()
{
super();
}
public ApplicationException(String message, Throwable cause)
{
super(message, cause);
}
public ApplicationException(Throwable cause)
{
super(cause);
}
public ApplicationException(String msg)
{
super(msg);
}
public String getInternalErrorMessage()
{
Throwable cause = this.getCause();
if(cause != null)
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
cause.printStackTrace(pw);
return sw.toString();
}
return null;
}
}
步骤2:通过实现ExceptionMapper接口创建ExceptionHandlers。
**
* ResourceNotFoundExceptionHandler.java
*
package com.sivalabs.resteasydemo;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.springframework.stereotype.Component;
@Provider
@Component
public class ResourceNotFoundExceptionHandler implements ExceptionMapper<ResourceNotFoundException>
{
@Override
public Response toResponse(ResourceNotFoundException ex)
For simplicity I am preparing error xml by hand.
Ideally we should create an ErrorResponse class to hold the error info.
String msg = ex.getMessage();
StringBuilder response = new StringBuilder('<response>');
response.append('<status>failed<status>');
response.append('<message>'+msg+'<message>');
response.append('<response>');
return Response.serverError().entity(response.toString()).build();
}
}
**
* ApplicationExceptionHandler.java
*
package com.sivalabs.resteasydemo;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.springframework.stereotype.Component;
@Provider
@Component
public class ApplicationExceptionHandler implements ExceptionMapper<ApplicationException>
{
@Override
public Response toResponse(ApplicationException ex)
{
For simplicity I am preparing error xml by hand.
Ideally we should create an ErrorResponse class to hold the error info.
String msg = ex.getMessage();
String internalError = ex.getInternalErrorMessage();
StringBuilder response = new StringBuilder('<response>');
response.append('<status>failed<status>');
response.append('<message>'+msg+'<message>');
response.append('<internalError>'+internalError+'<internalError>');
response.append('<response>');
return Response.serverError().entity(response.toString()).build();
}
}
步骤#3:更新UserResource.getUserXMLById()方法以验证用户输入并引发相应的异常 。
@Path('{id}')
@GET
public Response getUserXMLById(@PathParam('id') Integer id)
{
if(id==null || id < 1 ){
throw new ApplicationException('User Id['+id+'] should not be less than 1.');
}
User user = userService.getById(id);
if(user==null ){
throw new ResourceNotFoundException('No User found with Id :['+id+']');
}
return Response.ok(user).build();
}
步骤4:通过发出以下请求,测试UserResource.getUserXMLById()服务方法。
case 1 : GET http:localhost:8080resteasy-demorestusers0
Response :
<response>
<status>failed<status>
<message>User Id[0] should not be less than 1.<message>
<internalError>null<internalError>
<response>
case 2: GET http:localhost:8080resteasy-demorestusers100
Response :
<response>
<status>failed<status>
<message>No User found with Id :[100]<message>
<response>
重要注意事项:
在Spring创建必要的对象时,我们应该让Spring知道@Provider类,以使它们在RESTEasy中注册。 我们可以通过两种方式做到这一点。
a)使用@Component注释提供程序类
b)使用组件扫描的包含过滤器。
<context:component-scan base-package ='com.sivalabs.springdemo'>
<context:include-filter expression ='javax.ws.rs.ext.Provider'type ='annotation'/> </ context:component-scan>
RESTEasy教程系列
参考: RESTEasy教程第3部分–来自我们的JCG合作伙伴 Siva Reddy的“ 异常处理” ,位于“ 技术上的我的实验”博客上。
翻译自: https://www.javacodegeeks.com/2012/06/resteasy-tutorial-part-3-exception.html