创建自定义异常
要处理基于 JAX-RS 的 Web 服务中的自定义异常,我们应该创建一个异常类,然后实现 ExceptionMapper
接口。
package com.onitroad.jersey; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; @Provider public class MissingFileException extends Exception implements ExceptionMapper<MissingFileException> { private static final long serialVersionUID = 1L; public MissingFileException() { super("No File found with given name !!"); } public MissingFileException(String string) { super(string); } @Override public Response toResponse(MissingFileException exception) { return Response.status(404).entity(exception.getMessage()) .type("text/plain").build(); } }
https://onitroad.com 更多教程
如何从 REST API 抛出异常
现在,当在所需位置找不到用户请求的文件时,我们可以抛出“MissingFileException”。
package com.onitroad.jersey; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.StreamingOutput; @Path("/download") public class JerseyService { @GET @Path("/{fileName}") public Response downloadPdfFile(final @PathParam("fileName") String fileName) throws MissingFileException { final String fullFilePath = "C:/temp/" + fileName; File file = new File(fullFilePath); if(file.exists() == false){ throw new MissingFileException(fileName + " does not existing on this server !!"); } StreamingOutput fileStream = new StreamingOutput() { @Override public void write(java.io.OutputStream output) throws IOException { try { java.nio.file.Path path = Paths.get(fullFilePath); byte[] data = Files.readAllBytes(path); output.write(data); output.flush(); } catch (IOException e) { throw new IOException("Error while reading file :: '"+fileName+"' !!"); } } }; return Response .ok(fileStream, MediaType.APPLICATION_OCTET_STREAM) .header("content-disposition","attachment; filename = '"+fileName) .build(); } }
Jersey 异常处理示例
现在是测试 jersey 异常映射器的时候了。
请求存在的文件
将返回200状态,没有异常
请求不存在的文件
将返回404错误
未捕获的异常处理
如果我们想在进入用户屏幕之前处理所有未捕获的异常,则必须映射 Throwable
本身。
package com.onitroad.jersey.provider; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; @Provider public class UncaughtException extends Throwable implements ExceptionMapper<Throwable> { private static final long serialVersionUID = 1L; @Override public Response toResponse(Throwable exception) { return Response.status(500).entity("Something bad happened. Please try again !!").type("text/plain").build(); } }
日期:2020-09-17 00:16:31 来源:oir作者:oir