index.mdx 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. ---
  2. title: "Error Handling"
  3. showtoc: true
  4. ---
  5. Errors in Vendure can be divided into two categories:
  6. * Unexpected errors
  7. * Expected errors
  8. These two types have different meanings and are handled differently from one another.
  9. ## Unexpected Errors
  10. This type of error occurs when something goes unexpectedly wrong during the processing of a request. Examples include internal server errors, database connectivity issues, lacking permissions for a resource, etc. In short, these are errors that are *not supposed to happen*.
  11. Internally, these situations are handled by throwing an Error:
  12. ```ts
  13. const customer = await this.findOneByUserId(ctx, user.id);
  14. // in this case, the customer *should always* be found, and if
  15. // not then something unknown has gone wrong...
  16. if (!customer) {
  17. throw new InternalServerError('error.cannot-locate-customer-for-user');
  18. }
  19. ```
  20. In the GraphQL APIs, these errors are returned in the standard `errors` array:
  21. ```json
  22. {
  23. "errors": [
  24. {
  25. "message": "You are not currently authorized to perform this action",
  26. "locations": [
  27. {
  28. "line": 2,
  29. "column": 2
  30. }
  31. ],
  32. "path": [
  33. "me"
  34. ],
  35. "extensions": {
  36. "code": "FORBIDDEN"
  37. }
  38. }
  39. ],
  40. "data": {
  41. "me": null
  42. }
  43. }
  44. ```
  45. So your client applications need a generic way of detecting and handling this kind of error. For example, many http client libraries support "response interceptors" which can be used to intercept all API responses and check the `errors` array.
  46. :::note
  47. GraphQL will return a `200` status even if there are errors in the `errors` array. This is because in GraphQL it is still possible to return good data _alongside_ any errors.
  48. :::
  49. Here's how it might look in a simple Fetch-based client:
  50. ```ts title="src/client.ts"
  51. export function query(document: string, variables: Record<string, any> = {}) {
  52. return fetch(endpoint, {
  53. method: 'POST',
  54. headers,
  55. credentials: 'include',
  56. body: JSON.stringify({
  57. query: document,
  58. variables,
  59. }),
  60. })
  61. .then(async (res) => {
  62. if (!res.ok) {
  63. const body = await res.json();
  64. throw new Error(body);
  65. }
  66. const newAuthToken = res.headers.get('vendure-auth-token');
  67. if (newAuthToken) {
  68. localStorage.setItem(AUTH_TOKEN_KEY, newAuthToken);
  69. }
  70. return res.json();
  71. })
  72. .catch((err) => {
  73. // This catches non-200 responses, such as malformed queries or
  74. // network errors. Handle this with your own error handling logic.
  75. // For this demo we just show an alert.
  76. window.alert(err.message);
  77. })
  78. .then((result) => {
  79. // highlight-start
  80. // We check for any GraphQL errors which would be in the
  81. // `errors` array of the response body:
  82. if (Array.isArray(result.errors)) {
  83. // It looks like we have an unexpected error.
  84. // At this point you could take actions like:
  85. // - logging the error to a remote service
  86. // - displaying an error popup to the user
  87. // - inspecting the `error.extensions.code` to determine the
  88. // type of error and take appropriate action. E.g. a
  89. // in response to a FORBIDDEN_ERROR you can redirect the
  90. // user to a login page.
  91. // In this example we just display an alert:
  92. const errorMessage = result.errors.map((e) => e.message).join('\n');
  93. window.alert(`Unexpected error caught:\n\n${errorMessage}`);
  94. }
  95. // highlight-end
  96. return result;
  97. });
  98. }
  99. ```
  100. ## Expected errors (ErrorResults)
  101. This type of error represents a well-defined result of (typically) a GraphQL mutation which is not considered "successful". For example, when using the `applyCouponCode` mutation, the code may be invalid, or it may have expired. These are examples of "expected" errors and are named in Vendure "ErrorResults". These ErrorResults are encoded into the GraphQL schema itself.
  102. ErrorResults all implement the `ErrorResult` interface:
  103. ```graphql
  104. interface ErrorResult {
  105. errorCode: ErrorCode!
  106. message: String!
  107. }
  108. ```
  109. Some ErrorResults add other relevant fields to the type:
  110. ```graphql
  111. "Returned if there is an error in transitioning the Order state"
  112. type OrderStateTransitionError implements ErrorResult {
  113. errorCode: ErrorCode!
  114. message: String!
  115. transitionError: String!
  116. fromState: String!
  117. toState: String!
  118. }
  119. ```
  120. Operations that may return ErrorResults use a GraphQL `union` as their return type:
  121. ```graphql
  122. type Mutation {
  123. "Applies the given coupon code to the active Order"
  124. applyCouponCode(couponCode: String!): ApplyCouponCodeResult!
  125. }
  126. union ApplyCouponCodeResult = Order
  127. | CouponCodeExpiredError
  128. | CouponCodeInvalidError
  129. | CouponCodeLimitError
  130. ```
  131. ### Querying an ErrorResult union
  132. When performing an operation of a query or mutation which returns a union, you will need to use the [GraphQL conditional fragment](https://graphql.org/learn/schema/#union-types) to select the desired fields:
  133. ```graphql
  134. mutation ApplyCoupon($code: String!) {
  135. applyCouponCode(couponCode: $code) {
  136. __typename
  137. ...on Order {
  138. id
  139. couponCodes
  140. totalWithTax
  141. }
  142. # querying the ErrorResult fields
  143. # "catches" all possible errors
  144. ...on ErrorResult {
  145. errorCode
  146. message
  147. }
  148. # you can also specify particular fields
  149. # if your client app needs that specific data
  150. # as part of handling the error.
  151. ...on CouponCodeLimitError {
  152. limit
  153. }
  154. }
  155. }
  156. ```
  157. :::note
  158. The `__typename` field is added by GraphQL to _all_ object types, so we can include it no matter whether the result will end up being
  159. an `Order` object or an `ErrorResult` object. We can then use the `__typename` value to determine what kind of object we have received.
  160. Some clients such as Apollo Client will automatically add the `__typename` field to all queries and mutations. If you are using a client which does not do this, you will need to add it manually.
  161. :::
  162. Here's how a response would look in both the success and error result cases:
  163. <Tabs>
  164. <TabItem value="Success case" label="Success case" >
  165. ```json
  166. {
  167. "data": {
  168. "applyCouponCode": {
  169. // highlight-next-line
  170. "__typename": "Order",
  171. "id": "123",
  172. "couponCodes": ["VALID-CODE"],
  173. "totalWithTax": 12599,
  174. }
  175. }
  176. }
  177. ```
  178. </TabItem>
  179. <TabItem value="Error case" label="Error case" >
  180. ```json
  181. {
  182. "data": {
  183. "applyCouponCode": {
  184. // highlight-next-line
  185. "__typename": "CouponCodeLimitError",
  186. "errorCode": "COUPON_CODE_LIMIT_ERROR",
  187. "message": "Coupon code cannot be used more than once per customer",
  188. // highlight-next-line
  189. "limit": 1
  190. }
  191. }
  192. }
  193. ```
  194. </TabItem>
  195. </Tabs>
  196. ### Handling ErrorResults in plugin code
  197. If you are writing a plugin which deals with internal Vendure service methods that may return ErrorResults,
  198. then you can use the `isGraphQlErrorResult()` function to check whether the result is an ErrorResult:
  199. ```ts
  200. import { Injectable} from '@nestjs/common';
  201. import { isGraphQlErrorResult, Order, OrderService, OrderState, RequestContext } from '@vendure/core';
  202. @Injectable()
  203. export class MyService {
  204. constructor(private orderService: OrderService) {}
  205. async myMethod(ctx: RequestContext, order: Order, newState: OrderState) {
  206. const transitionResult = await this.orderService.transitionToState(ctx, order.id, newState);
  207. if (isGraphQlErrorResult(transitionResult)) {
  208. // The transition failed with an ErrorResult
  209. throw transitionResult;
  210. } else {
  211. // TypeScript will correctly infer the type of `transitionResult` to be `Order`
  212. return transitionResult;
  213. }
  214. }
  215. }
  216. ```
  217. ### Handling ErrorResults in client code
  218. Because we know all possible ErrorResult that may occur for a given mutation, we can handle them in an exhaustive manner. In other
  219. words, we can ensure our storefront has some sensible response to all possible errors. Typically this will be done with
  220. a `switch` statement:
  221. ```ts
  222. const result = await query(APPLY_COUPON_CODE, { code: 'INVALID-CODE' });
  223. switch (result.applyCouponCode.__typename) {
  224. case 'Order':
  225. // handle success
  226. break;
  227. case 'CouponCodeExpiredError':
  228. // handle expired code
  229. break;
  230. case 'CouponCodeInvalidError':
  231. // handle invalid code
  232. break;
  233. case 'CouponCodeLimitError':
  234. // handle limit error
  235. break;
  236. default:
  237. // any other ErrorResult can be handled with a generic error message
  238. }
  239. ```
  240. If we combine this approach with [GraphQL code generation](/storefront/codegen/), then TypeScript will even be able to
  241. help us ensure that we have handled all possible ErrorResults:
  242. ```ts
  243. // Here we are assuming that the APPLY_COUPON_CODE query has been generated
  244. // by the codegen tool, and therefore has the
  245. // type `TypedDocumentNode<ApplyCouponCode, ApplyCouponCodeVariables>`.
  246. const result = await query(APPLY_COUPON_CODE, { code: 'INVALID-CODE' });
  247. switch (result.applyCouponCode.__typename) {
  248. case 'Order':
  249. // handle success
  250. break;
  251. case 'CouponCodeExpiredError':
  252. // handle expired code
  253. break;
  254. case 'CouponCodeInvalidError':
  255. // handle invalid code
  256. break;
  257. case 'CouponCodeLimitError':
  258. // handle limit error
  259. break;
  260. default:
  261. // highlight-start
  262. // this line will cause a TypeScript error if there are any
  263. // ErrorResults which we have not handled in the switch cases
  264. // above.
  265. const _exhaustiveCheck: never = result.applyCouponCode;
  266. // highlight-end
  267. }
  268. ```
  269. ## Live example
  270. Here is a live example which the handling of unexpected errors as well as ErrorResults:
  271. <Stackblitz id='vendure-docs-error-handling' />