异常映射 - org.jboss.resteasy.spi.UnhandledException:exception.DenemeException:off bu exler

时间:2011-05-05 06:44:39

标签: java jax-rs resteasy

我有一个安静的应用程序,可以将一些联系人导入数据库。我想在没有通过restful上传文件时抛出异常。所以我写了一个异常类DenemeException,我想发送状态404,当我运行代码我得到这个错误org.jboss.resteasy.spi.UnhandledException:exception.DenemeException:off bu exler 你可以帮我吗?

DenemeExceptionMapper.java

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




@Provider
public class DenemeExceptionMapper implements ExceptionMapper<DenemeException> {
     @Override
 public Response toResponse(DenemeException ex){
     return Response.status(Response.Status.FORBIDDEN).entity(ex.getMessage()).type(MediaType.TEXT_PLAIN).build();
 }

}

DenemeException.java

public class DenemeException extends Exception {
/**
 * 
 */
private static final long serialVersionUID = 1L;

public DenemeException(String message) {
    super(message);
}

}

我的休息控制器

@POST
@Path("/import")
@Produces({"application/xml","application/json"})
public String saveContacts (@Context HttpServletRequest request, @Context HttpServletResponse response,
         @QueryParam("alt") String alt) throws DenemeException {

    byte[] content = null;

    FileItemStream item = null;
    try{
    ServletFileUpload upload = new ServletFileUpload();
    FileItemIterator iterator = upload.getItemIterator(request);

    while (iterator.hasNext()) {
        item = iterator.next();
        if ("fileUpload".equals(item.getFieldName())){

            content = IOUtils.toByteArray(item.openStream());

          }
        }
    }
    catch(Exception e){
        System.out.println("hata oldu");
        throw new DenemeException("off bu exler");
    }

1 个答案:

答案 0 :(得分:1)

您需要使用Application注册ExceptionMapper,例如

public class HelloWorldApplication extends Application {

    private Set<Object> singletons = new HashSet();
    private Set<Class<?>> empty = new HashSet();

    public HelloWorldApplication() {
        // ADD YOUR RESTFUL RESOURCES HERE
        this.singletons.add(new SimpleServiceImpl());
        this.singletons.add(new AuthenticationServiceImpl());
        this.singletons.add(new DenemeExceptionMapper());  //<<< -- HERE IS YOUR EXCEPTION MAPPER !
    }

    public Set<Class<?>> getClasses() {
        return this.empty;
    }

    public Set<Object> getSingletons() {
        return this.singletons;
    }
}