项目作者: cdimascio

项目描述 :
⚡Customizable errors for RESTful and HTTP services.
高级语言: Java
项目地址: git://github.com/cdimascio/japi-errors.git
创建时间: 2018-10-22T16:32:11Z
项目社区:https://github.com/cdimascio/japi-errors

开源协议:Apache License 2.0

下载


japi-errors

Customizable errors for RESTful and HTTP services.



Out of the box, japi-errors provides two error formats or enables you to provide your own.

All ‘out of the box’ errors are Jackson ready and can be serialized as JSON, XML, and YAML. If you’d like to use GSON or something else, create a custom error creator.

Install

Gradle

  1. compile 'io.github.cdimascio:japi-errors:1.3.1'

Maven

  1. <dependency>
  2. <groupId>io.github.cdimascio</groupId>
  3. <artifactId>japi-errors</artifactId>
  4. <version>1.3.1</version>
  5. </dependency>

Usage

Import error methods

  1. import static io.github.cdimascio.japierrors.ApiError.badRequest;
  2. // ...

Throw any HTTP error and optionally pass an exception or custom message.

  1. throw notFound();
  2. throw badRequest("id required.");
  3. throw internalServerError(exception);
  4. // ...

Assign

  1. ApiError error = unauthorized();

See examples with Spring MVC

Configure

japi-errors supports two error formats “out of the box”. They are enabled as follows:

  1. ApiError.creator(ApiErrorCreators.BASIC); // The default
  2. ApiError.creator(ApiErrorCreators.WCP);

Basic (default)

  1. {
  2. "code": 400,
  3. "error": "id required."
  4. }

WCP

  1. {
  2. "trace": "1f96a430-dfd8-11e8-9f32-f2801f1b9fd1",
  3. "errors": [{
  4. "code": "bad_request",
  5. "message": "id required."
  6. }]
  7. }

Customize

japi-errors enables developers to craft custom error objects. To do so, implement the ApiErrorCreator interface, then pass an instance of your creator to ApiError.creator(myApiErrorCreator)

To see a working example, check out this source code

Example:

  1. // Create an api error creator
  2. public class MyApiErrorCreator implements IApiErrorCreator {
  3. @Override
  4. public ApiError create(HttpStatus status, String message) {
  5. return new MyApiError(message);
  6. }
  7. @Override
  8. public ApiError create(HttpStatus status, Throwable t) {
  9. return new MyApiError(t.getMessage());
  10. }
  11. }
  1. // Create a custom api error object
  2. // Add Json ignore properties (see source code link above)
  3. public class MyApiError extends ApiError {
  4. @JsonProperty
  5. private String message;
  6. MyApiError() {
  7. super();
  8. }
  9. MyApiError(String message) {
  10. this.message = message;
  11. }
  12. public String getMessage() {
  13. return message;
  14. }
  15. }

Examples

Check out the following examples to see japi-errors in use:

License

Apache 2