{"id":13458759,"url":"https://github.com/zalando/problem","last_synced_at":"2025-03-24T15:32:03.395Z","repository":{"id":35439399,"uuid":"39705783","full_name":"zalando/problem","owner":"zalando","description":"A Java library that implements application/problem+json","archived":false,"fork":false,"pushed_at":"2025-03-17T17:22:55.000Z","size":1425,"stargazers_count":910,"open_issues_count":21,"forks_count":88,"subscribers_count":29,"default_branch":"main","last_synced_at":"2025-03-17T18:31:34.282Z","etag":null,"topics":["error","exception","java","json","microservices","problem","rfc7807"],"latest_commit_sha":null,"homepage":"https://zalando.github.io/problem","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/zalando.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":".github/CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":".github/CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2015-07-25T23:03:12.000Z","updated_at":"2025-03-17T17:23:00.000Z","dependencies_parsed_at":"2023-02-18T03:01:34.054Z","dependency_job_id":"946946aa-9df9-46d1-a334-1da99751060a","html_url":"https://github.com/zalando/problem","commit_stats":{"total_commits":429,"total_committers":21,"mean_commits":"20.428571428571427","dds":0.5641025641025641,"last_synced_commit":"6a4b1ed10669028f5005622230ce8463ad8be59b"},"previous_names":[],"tags_count":24,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zalando%2Fproblem","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zalando%2Fproblem/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zalando%2Fproblem/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zalando%2Fproblem/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/zalando","download_url":"https://codeload.github.com/zalando/problem/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245298210,"owners_count":20592563,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["error","exception","java","json","microservices","problem","rfc7807"],"created_at":"2024-07-31T09:00:56.907Z","updated_at":"2025-03-24T15:31:58.380Z","avatar_url":"https://github.com/zalando.png","language":"Java","readme":"# Problem\n\n[![Bubble Gum on Shoe](docs/bubble-gum.jpg)](https://pixabay.com/en/bubble-gum-shoes-glue-dirt-438404/)\n\n[![Stability: Sustained](https://masterminds.github.io/stability/sustained.svg)](https://masterminds.github.io/stability/sustained.html)\n![Build Status](https://github.com/zalando/problem/workflows/build/badge.svg)\n[![Coverage Status](https://img.shields.io/coveralls/zalando/problem/main.svg)](https://coveralls.io/r/zalando/problem)\n[![Code Quality](https://img.shields.io/codacy/grade/fff557c57a9345d1afba5cc234cfbbd7/main.svg)](https://www.codacy.com/app/whiskeysierra/problem)\n[![Javadoc](http://javadoc.io/badge/org.zalando/problem.svg)](http://www.javadoc.io/doc/org.zalando/problem)\n[![Release](https://img.shields.io/github/release/zalando/problem.svg)](https://github.com/zalando/problem/releases)\n[![Maven Central](https://img.shields.io/maven-central/v/org.zalando/problem.svg)](https://maven-badges.herokuapp.com/maven-central/org.zalando/problem)\n[![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/zalando/problem/main/LICENSE)\n\n\u003e **Problem** noun, /ˈpɹɒbləm/: A difficulty that has to be resolved or dealt with.\n\n*Problem* is a library that implements \n[`application/problem+json`](https://tools.ietf.org/html/rfc7807).\nIt comes with an extensible set of interfaces/implementations as well as convenient functions for every day use.\nIt's decoupled from any JSON library, but contains a separate module for Jackson.\n\n## Features\n\n- proposes a common approach for expressing errors in REST API implementations\n- compatible with `application/problem+json`\n\n## Dependencies\n\n- Java 8\n- Any build tool using Maven Central, or direct download\n- Jackson (optional)\n- Gson (optional)\n\n## Installation\n\nAdd the following dependency to your project:\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003eorg.zalando\u003c/groupId\u003e\n    \u003cartifactId\u003eproblem\u003c/artifactId\u003e\n    \u003cversion\u003e${problem.version}\u003c/version\u003e\n\u003c/dependency\u003e\n\u003cdependency\u003e\n    \u003cgroupId\u003eorg.zalando\u003c/groupId\u003e\n    \u003cartifactId\u003ejackson-datatype-problem\u003c/artifactId\u003e\n    \u003cversion\u003e${problem.version}\u003c/version\u003e\n\u003c/dependency\u003e\n\u003cdependency\u003e\n    \u003cgroupId\u003eorg.zalando\u003c/groupId\u003e\n    \u003cartifactId\u003eproblem-gson\u003c/artifactId\u003e\n    \u003cversion\u003e${problem.version}\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\n### Java Modules\n\nEven though the minimum requirement is still Java 8, all modules are Java 9 compatible:\n\n```java\nmodule org.example {\n    requires org.zalando.problem;\n    // pick needed dependencies\n    requires org.zalando.problem.jackson;\n    requires org.zalando.problem.gson;\n}\n```\n\n## Configuration\n\nIn case you're using Jackson, make sure you register the module with your `ObjectMapper`:\n\n```java\nObjectMapper mapper = new ObjectMapper()\n    .registerModule(new ProblemModule());\n```\n\nAlternatively, you can use the SPI capabilities:\n\n```java\nObjectMapper mapper = new ObjectMapper()\n    .findAndRegisterModules();\n```\n\n## Usage\n\n### Creating problems\n\nThere are different ways to express problems. Ranging from limited, but easy-to-use to highly flexible and extensible, \nyet with slightly more effort:\n\n#### Generic\n\nThere are cases in which an [HTTP status code](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes) is basically \nenough to convey the necessary information. Everything you need is the status you want to respond with and we will \ncreate a problem from it:\n\n```java\nProblem.valueOf(Status.NOT_FOUND);\n```\n\nWill produce this:\n\n```json\n{\n  \"title\": \"Not Found\",\n  \"status\": 404\n}\n```\n\nAs specified by [Predefined Problem Types](https://tools.ietf.org/html/rfc7807#section-4.2):\n\n\u003e The \"about:blank\" URI, when used as a problem type,\n\u003e indicates that the problem has no additional semantics beyond that of\n\u003e the HTTP status code.\n  \n\u003e When \"about:blank\" is used, the title SHOULD be the same as the\n\u003e recommended HTTP status phrase for that code (e.g., \"Not Found\" for\n\u003e 404, and so on), although it MAY be localized to suit client\n\u003e preferences (expressed with the Accept-Language request header).\n\nBut you may also have the need to add some little hint, e.g. as a custom detail of the problem:\n\n```java\nProblem.valueOf(Status.SERVICE_UNAVAILABLE, \"Database not reachable\");\n```\n\nWill produce this:\n\n```json\n{\n  \"title\": \"Service Unavailable\",\n  \"status\": 503,\n  \"detail\": \"Database not reachable\"\n}\n```\n\n#### Builder\n\nMost of the time you'll need to define specific problem types, that are unique to your application. And you want to \nconstruct problems in a more flexible way. This is where the *Problem Builder* comes into play. It offers a fluent API \nand allows to construct problem instances without the need to create custom classes:\n\n```java\nProblem.builder()\n    .withType(URI.create(\"https://example.org/out-of-stock\"))\n    .withTitle(\"Out of Stock\")\n    .withStatus(BAD_REQUEST)\n    .withDetail(\"Item B00027Y5QG is no longer available\")\n    .build();\n```\n\nWill produce this:\n\n```json\n{\n  \"type\": \"https://example.org/out-of-stock\",\n  \"title\": \"Out of Stock\",\n  \"status\": 400,\n  \"detail\": \"Item B00027Y5QG is no longer available\"\n}\n```\n\nAlternatively you can add custom properties, i.e. others than `type`, `title`, `status`, `detail` and `instance`:\n\n```java\nProblem.builder()\n    .withType(URI.create(\"https://example.org/out-of-stock\"))\n    .withTitle(\"Out of Stock\")\n    .withStatus(BAD_REQUEST)\n    .withDetail(\"Item B00027Y5QG is no longer available\")\n    .with(\"product\", \"B00027Y5QG\")\n    .build();\n```\n\nWill produce this:\n\n```json\n{\n  \"type\": \"https://example.org/out-of-stock\",\n  \"title\": \"Out of Stock\",\n  \"status\": 400,\n  \"detail\": \"Item B00027Y5QG is no longer available\",\n  \"product\": \"B00027Y5QG\"\n}\n```\n\n#### Custom Problems\n\nThe highest degree of flexibility and customizability is achieved by implementing `Problem` directly. This is \nespecially convenient if you refer to it in a lot of places, i.e. it makes it easier to share. Alternatively you can\nextend `AbstractThrowableProblem`:\n\n```java\n@Immutable\npublic final class OutOfStockProblem extends AbstractThrowableProblem {\n\n    static final URI TYPE = URI.create(\"https://example.org/out-of-stock\");\n\n    private final String product;\n\n    public OutOfStockProblem(final String product) {\n        super(TYPE, \"Out of Stock\", BAD_REQUEST, format(\"Item %s is no longer available\", product));\n        this.product = product;\n    }\n\n    public String getProduct() {\n        return product;\n    }\n\n}\n```\n\n```java\nnew OutOfStockProblem(\"B00027Y5QG\");\n```\n\nWill produce this:\n\n```json\n{\n  \"type\": \"https://example.org/out-of-stock\",\n  \"title\": \"Out of Stock\",\n  \"status\": 400,\n  \"detail\": \"Item B00027Y5QG is no longer available\",\n  \"product\": \"B00027Y5QG\"\n}\n```\n\n### Throwing problems\n\n*Problems* have a loose, yet direct connection to *Exceptions*. Most of the time you'll find yourself transforming one \ninto the other. To make this a little bit easier there is an abstract `Problem` implementation that subclasses \n`RuntimeException`: the `ThrowableProblem`. It allows to throw problems and is already in use by all default \nimplementations. Instead of implementing the `Problem` interface, just inherit from `AbstractThrowableProblem`:\n\n```java\npublic final class OutOfStockProblem extends AbstractThrowableProblem {\n    // constructor\n}\n```\n\nIf you already have an exception class that you want to extend, you should implement the \"marker\" interface `Exceptional`:\n\n```java\npublic final class OutOfStockProblem extends BusinessException implements Exceptional\n```\n\nThe Jackson support module will recognize this interface and deal with the inherited properties from `Throwable` \naccordingly. Note: This interface only exists, because `Throwable` is a concrete class, rather than an interface.\n\n### Handling problems\n\nReading problems is very specific to the JSON parser in use. This section assumes you're using Jackson, in which case \nreading/parsing problems usually boils down to this:\n\n```java\nProblem problem = mapper.readValue(.., Problem.class);\n```\n\nIf you're using Jackson, please make sure you understand its \n[Polymorphic Deserialization](https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization) feature. The supplied \nJackson module makes heavy use of it. Considering you have a custom problem type `OutOfStockProblem`, you'll need to \nregister it as a subtype:\n\n```java\nmapper.registerSubtypes(OutOfStockProblem.class);\n```\nYou also need to make sure you assign a `@JsonTypeName` to it and declare a `@JsonCreator`:\n\n```java\n@JsonTypeName(OutOfStockProblem.TYPE_VALUE)\npublic final class OutOfStockProblem implements Problem {\n\n    @JsonCreator\n    public OutOfStockProblem(final String product) {\n```\n\nJackson is now able to deserialize specific problems into their respective types. By default, e.g. if a type is not \nassociated with a class, it will fallback to a `DefaultProblem`. \n\n### Catching problems\n\nIf you read about [Throwing problems](#throwing-problems) already, you should be familiar with `ThrowableProblem`. \nThis can be helpful if you read a problem, as a response from a server, and what to find out what it actually is. \nMultiple `if` statements with `instanceof` checks could be an option, but usually nicer is this:\n\n```java\ntry {\n    throw mapper.readValue(.., ThrowableProblem.class);\n} catch (OutOfStockProblem e) {\n    tellTheCustomerTheProductIsNoLongerAvailable(e.getProduct());\n} catch (InsufficientFundsProblem e) {\n    askCustomerToUseDifferentPaymentMethod(e.getBalance(), e.getDebit());\n} catch (InvalidCouponProblem e) {\n    askCustomerToUseDifferentCoupon(e.getCouponCode());\n} catch (ThrowableProblem e) {\n    tellTheCustomerSomethingWentWrong();\n}\n```\n\nIf you used the `Exceptional` interface rather than `ThrowableProblem` you have to adjust your code a little bit:\n\n```java\ntry {\n    throw mapper.readValue(.., Exceptional.class).propagate();\n} catch (OutOfStockProblem e) {\n    ...\n```\n\n### Stack traces and causal chains\n\nExceptions in Java can be chained/nested using *causes*. `ThrowableProblem` adapts the pattern seamlessly to problems:\n\n```java\nThrowableProblem problem = Problem.builder()\n    .withType(URI.create(\"https://example.org/order-failed\"))\n    .withTitle(\"Order failed\")\n    .withStatus(BAD_REQUEST)\n    .withCause(Problem.builder()\n      .withType(URI.create(\"https://example.org/out-of-stock\"))\n      .withTitle(\"Out of Stock\")\n      .withStatus(BAD_REQUEST)\n      .build())\n    .build();\n    \nproblem.getCause(); // standard API of java.lang.Throwable\n```\n\nWill produce this:\n\n```json\n{\n  \"type\": \"https://example.org/order-failed\",\n  \"title\": \"Order failed\",\n  \"status\": 400,\n  \"cause\": {\n    \"type\": \"https://example.org/out-of-stock\",\n    \"title\": \"Out of Stock\",\n    \"status\": 400,\n    \"detail\": \"Item B00027Y5QG is no longer available\"\n  }\n}\n```\n\nAnother important aspect of exceptions are stack traces, but since they leak implementation details to the outside world, \n[**we strongly advise against exposing them**](http://zalando.github.io/restful-api-guidelines/#177)\nin problems. That being said, there is a legitimate use case when you're debugging an issue on an integration environment\nand you don't have direct access to the log files. Serialization of stack traces can be enabled on the problem module:\n\n```java\nObjectMapper mapper = new ObjectMapper()\n    .registerModule(new ProblemModule().withStackTraces());\n```\n\nAfter enabling stack traces all problems will contain a `stacktrace` property:\n\n```json\n{\n  \"type\": \"about:blank\",\n  \"title\": \"Unprocessable Entity\",\n  \"status\": 400,\n  \"stacktrace\": [\n    \"org.example.Example.execute(Example.java:17)\",\n    \"org.example.Example.main(Example.java:11)\"\n  ]\n}\n```\n\nSince we discourage the  serialization of them, there is currently, by design, no way to deserialize them from JSON.\nNevertheless the runtime will fill in the stack trace when the problem instance is created. That stack trace is usually\nnot 100% correct, since it looks like the exception originated inside your deserialization framework. *Problem* comes\nwith a special service provider interface `StackTraceProcessor` that can be registered using the \n[`ServiceLoader` capabilities](http://docs.oracle.com/javase/8/docs/api/java/util/ServiceLoader.html). It can be used\nto modify the stack trace, e.g. remove all lines before your own client code, e.g. Jackson/HTTP client/etc.\n\n```java\npublic interface StackTraceProcessor {\n\n    Collection\u003cStackTraceElement\u003e process(final Collection\u003cStackTraceElement\u003e elements);\n\n}\n```\n\nBy default no processing takes place.\n\n## Getting help\n\nIf you have questions, concerns, bug reports, etc, please file an issue in this repository's Issue Tracker.\n\n## Getting involved\n\nTo contribute, simply make a pull request and add a brief description (1-2 sentences) of your addition or change. \nFor more details check the [contribution guidelines](.github/CONTRIBUTING.md).\n\n## Credits and references\n\n### Spring Framework\n\nUsers of the [Spring Framework](https://spring.io) are highly encouraged to check out [Problems for Spring Web MVC](https://github.com/zalando/problem-spring-web), a library that seemlessly integrates problems into Spring.\n\n### Micronaut Framework\nUsers of the [Micronaut Framework](https://micronaut.io) are highly encouraged to check out [Micronaut Problem JSON\n](https://micronaut-projects.github.io/micronaut-problem-json/snapshot/guide/), a library that seemlessly integrates problems into Micronaut error processing.\n\n### Quarkus Framework\nUsers of the [Quarkus Framework](https://quarkus.io/) are highly encouraged to check out [Quarkus RESTeasy Problem Extension](https://github.com/TietoEVRY/quarkus-resteasy-problem/), a library that seemlessly integrates problems into Quarkus RESTeasy/JaxRS error processing. It also handles Problem-family exceptions from `org.zalando:problem` library.\n","funding_links":[],"categories":["Java","REST错误处理","\u003ca name=\"Java\"\u003e\u003c/a\u003eJava"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzalando%2Fproblem","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fzalando%2Fproblem","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzalando%2Fproblem/lists"}