resteasy 统一异常_RESTEasy教程第3部分:异常处理

resteasy 统一异常

在开发软件应用程序时,异常处理是显而易见的要求。 如果在处理用户请求时发生任何错误,我们应该向用户显示一个错误页面,其中包含详细的异常消息,错误代码(可选),更正输入和重试的提示(可选)以及实际根本原因(可选)等详细信息。 这也适用于RESTful Web服务。

但是,将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教程第1部分:基础

RESTEasy教程第2部分:Spring集成

RESTEasy教程第3部分–异常处理

参考: RESTEasy教程第3部分–来自我们的JCG合作伙伴 Siva Reddy的“ 异常处理” ,位于“ 我的实验在技术”博客上。


翻译自: https://www.javacodegeeks.com/2012/06/resteasy-tutorial-part-3-exception.html

resteasy 统一异常

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值