[Jersey] RESTful service starter-kit (1)

JAX-RS有提供類似AOP功能,我們可以集中處理所有的Exception。

Clean Code說到:


The short chapter seven of «Clean Code» is dedicated to error handling. The one point it stresses with vigor is:
Do not use checked exceptions!
The price of checked exceptions is an Open/Closed Principle violation. If you throw a checked exception from a method in your code and the catch is three levels above, you must declare that exception in the signature of each method between you and the catch. This means that a change at a low level of the software can force signature changes on many higher levels.
—Robert C. Martin, «Clean Code», page 107

我會習慣將checked exception轉成runtime exception,統一集中處理。

例如:只要沒有處理到的exception,一律回Internal Server Error

只要實作ExceptionMapper,選擇要捕捉exception放到generic,最後再加入@Provider就可以統一處理想要處理的Exception。

1
2
3
4
5
6
7
8
9
10
11
@Provider
public class GenericExceptionMapper implements ExceptionMapper<Throwable> {

@Override
public Response toResponse(Throwable exception) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(exception.getMessage())
.type(MediaType.APPLICATION_JSON)
.build();
}
}


Glassfish有提供LoggingFilter,可以自動log每個request和response。
假如對於輸出格式比較要求,可以實作屬於自己的LoggingFilter,實作方式可以參考LoggingFilter.java

使用LoggingFilter可以在web.xml或程式碼中開啟。可以參考Registering Resources and Providers in Jersey 2

例如:

client端發出:

http://localhost:8080/jersey-starterkit/hello```
1
2
3
4
5
6
7
8
9
10
11
12
server端會紀錄相關資訊:
```bash
15:34:40.087 [qtp1671915608-80] INFO application.MyApplication - 3 * Server has received a request on thread qtp1671915608-80
1 > GET http://localhost:8080/jersey-starterkit/hello
1 > Accept: */*
1 > Host: localhost:8080
1 > User-Agent: curl/7.37.1

15:34:40.091 [qtp1671915608-80] INFO application.MyApplication - 4 * Server responded with a response on thread qtp1671915608-80
2 < 200
2 < Content-Type: application/json
hello

程式碼:

https://github.com/pandaforme/jersey-starterkit

參考資料: