1 import { Table } from "docs-ui"
2
3 export const metadata = {
4 title: `${pageNumber} Throwing and Handling Errors`,
5 }
6
7 # {metadata.title}
8
9 In this guide, you'll learn how to throw errors in your Medusa application, how it affects an API route's response, and how to change the default error handler of your Medusa application.
10
11 ## Throw MedusaError
12
13 When throwing an error in your API routes, middlewares, workflows, or any customization, throw a `MedusaError` from the Medusa Framework.
14
15 The Medusa application's API route error handler then wraps your thrown error in a uniform object and returns it in the response.
16
17 For example:
18
19 ```ts
20 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
21 import { MedusaError } from "@medusajs/framework/utils"
22
23 export const GET = async (
24 req: MedusaRequest,
25 res: MedusaResponse
26 ) => {
27 if (!req.query.q) {
28 throw new MedusaError(
29 MedusaError.Types.INVALID_DATA,
30 "The `q` query parameter is required."
31 )
32 }
33
34 // ...
35 }
36 ```
37
38 The `MedusaError` class accepts two parameters in its constructor:
39
40 1. The first is the error's type. `MedusaError` has a static property `Types` that you can use. `Types` is an enum whose possible values are explained in the next section.
41 2. The second is the message to show in the error response.
42
43 ### Error Object in Response
44
45 The error object returned in the response has three properties:
46
47 - `type`: The error's type.
48 - `message`: The error message, if available.
49 - `code`: A common snake-case code. Its values can be:
50 - `invalid_request_error` for the `DUPLICATE_ERROR` type.
51 - `api_error` for the `DB_ERROR` type.
52 - `invalid_state_error` for the `CONFLICT` error type.
53 - `unknown_error` for any unidentified error type.
54 - For other error types, this property won't be available unless you provide a code as a third parameter to the `MedusaError` constructor.
55
56 ### MedusaError Types
57
58 <Table>
59 <Table.Header>
60 <Table.Row>
61 <Table.HeaderCell>
62 Type
63 </Table.HeaderCell>
64 <Table.HeaderCell>
65 Description
66 </Table.HeaderCell>
67 <Table.HeaderCell className="w-1/5">
68 Status Code
69 </Table.HeaderCell>
70 </Table.Row>
71 </Table.Header>
72 <Table.Body>
73 <Table.Row>
74 <Table.Cell>
75
76 `DB_ERROR`
77
78 </Table.Cell>
79 <Table.Cell>
80
81 Indicates a database error.
82
83 </Table.Cell>
84 <Table.Cell>
85
86 `500`
87
88 </Table.Cell>
89 </Table.Row>
90 <Table.Row>
91 <Table.Cell>
92
93 `DUPLICATE_ERROR`
94
95 </Table.Cell>
96 <Table.Cell>
97
98 Indicates a duplicate of a record already exists. For example, when trying to create a customer whose email is registered by another customer.
99
100 </Table.Cell>
101 <Table.Cell>
102
103 `422`
104
105 </Table.Cell>
106 </Table.Row>
107 <Table.Row>
108 <Table.Cell>
109
110 `INVALID_ARGUMENT` and `UNEXPECTED_STATE`
111
112 </Table.Cell>
113 <Table.Cell>
114
115 Indicates an error that occurred due to incorrect arguments or other unexpected state.
116
117 </Table.Cell>
118 <Table.Cell>
119
120 `500`
121
122 </Table.Cell>
123 </Table.Row>
124 <Table.Row>
125 <Table.Cell>
126
127 `INVALID_DATA`
128
129 </Table.Cell>
130 <Table.Cell>
131
132 Indicates a validation error.
133
134 </Table.Cell>
135 <Table.Cell>
136
137 `400`
138
139 </Table.Cell>
140 </Table.Row>
141 <Table.Row>
142 <Table.Cell>
143
144 `UNAUTHORIZED`
145
146 </Table.Cell>
147 <Table.Cell>
148
149 Indicates that a user is not authorized to perform an action or access a route.
150
151 </Table.Cell>
152 <Table.Cell>
153
154 `401`
155
156 </Table.Cell>
157 </Table.Row>
158 <Table.Row>
159 <Table.Cell>
160
161 `NOT_FOUND`
162
163 </Table.Cell>
164 <Table.Cell>
165
166 Indicates that the requested resource, such as a route or a record, isn't found.
167
168 </Table.Cell>
169 <Table.Cell>
170
171 `404`
172
173 </Table.Cell>
174 </Table.Row>
175 <Table.Row>
176 <Table.Cell>
177
178 `NOT_ALLOWED`
179
180 </Table.Cell>
181 <Table.Cell>
182
183 Indicates that an operation isn't allowed.
184
185 </Table.Cell>
186 <Table.Cell>
187
188 `400`
189
190 </Table.Cell>
191 </Table.Row>
192 <Table.Row>
193 <Table.Cell>
194
195 `CONFLICT`
196
197 </Table.Cell>
198 <Table.Cell>
199
200 Indicates that a request conflicts with another previous or ongoing request. The error message in this case is ignored in favor of a default message. Refer to the [note below](#conflict-error-messages) for details.
201
202 </Table.Cell>
203 <Table.Cell>
204
205 `409`
206
207 </Table.Cell>
208 </Table.Row>
209 <Table.Row>
210 <Table.Cell>
211
212 `PAYMENT_AUTHORIZATION_ERROR`
213
214 </Table.Cell>
215 <Table.Cell>
216
217 Indicates an error has occurred while authorizing a payment.
218
219 </Table.Cell>
220 <Table.Cell>
221
222 `422`
223
224 </Table.Cell>
225 </Table.Row>
226 <Table.Row>
227 <Table.Cell>
228
229 Other error types
230
231 </Table.Cell>
232 <Table.Cell>
233
234 Any other error type results in an `unknown_error` code and message.
235
236 </Table.Cell>
237 <Table.Cell>
238
239 `500`
240
241 </Table.Cell>
242 </Table.Row>
243 </Table.Body>
244 </Table>
245
246 ### Conflict Error Messages
247
248 The error handler replaces the message of a `CONFLICT` error with the following default message:
249
250 ```plain
251 The request conflicted with another request. You may retry the request with the provided Idempotency-Key.
252 ```
253
254 So, only throw a `CONFLICT` error for internal conflicts, such as a request that conflicts with an ongoing transaction or a lock that another process holds. The client doesn't need details about these conflicts, and the default message avoids exposing internal implementation details.
255
256 <Note title="Tip">
257
258 If the client needs the details of the conflict, throw a `NOT_ALLOWED` error instead. Its message reaches the client, but the response has a `400` status code rather than `409`.
259
260 </Note>
261
262 ---
263
264 ## Override Error Handler
265
266 The `defineMiddlewares` function used to apply middlewares on routes accepts an `errorHandler` in its object parameter. Use it to override the default error handler for API routes.
267
268 <Note>
269
270 This error handler will also be used for errors thrown in Medusa's API routes and resources.
271
272 </Note>
273
274 For example, create `src/api/middlewares.ts` with the following:
275
276 ```ts title="src/api/middlewares.ts" collapsibleLines="1-8" expandMoreLabel="Show Imports"
277 import {
278 defineMiddlewares,
279 MedusaNextFunction,
280 MedusaRequest,
281 MedusaResponse,
282 } from "@medusajs/framework/http"
283 import { MedusaError } from "@medusajs/framework/utils"
284
285 export default defineMiddlewares({
286 errorHandler: (
287 error: MedusaError | any,
288 req: MedusaRequest,
289 res: MedusaResponse,
290 next: MedusaNextFunction
291 ) => {
292 res.status(400).json({
293 error: "Something happened.",
294 })
295 },
296 })
297 ```
298
299 The `errorHandler` property's value is a function that accepts four parameters:
300
301 1. The error thrown. Its type can be `MedusaError` or any other error type.
302 2. A request object of type `MedusaRequest`.
303 3. A response object of type `MedusaResponse`.
304 4. A function of type `MedusaNextFunction` that executes the next middleware in the stack.
305
306 This example overrides Medusa's default error handler with a handler that always returns a `400` status code with the same message.
307
308 ### Re-Use Default Error Handler
309
310 In some use cases, you may not want to override the default error handler but rather perform additional actions as part of the original error handler. For example, you might want to capture the error in a third-party service like Sentry.
311
312 In those cases, you can import the default error handler from the Medusa Framework and use it in your custom error handler, along with your custom logic.
313
314 For example:
315
316 export const defaultErrorHandlerHighlights = [
317 ["3", "errorHandler", "Import the default error handler."],
318 ["12", "originalErrorHandler", "Get the original error handler function."],
319 ["23", "originalErrorHandler", "Re-use the original error handler after your custom logic."],
320 ]
321
322 ```ts title="src/api/middlewares.ts" highlights={defaultErrorHandlerHighlights}
323 import {
324 defineMiddlewares,
325 errorHandler,
326 MedusaNextFunction,
327 MedusaRequest,
328 MedusaResponse,
329 } from "@medusajs/framework/http"
330 import { MedusaError } from "@medusajs/framework/utils"
331 // assuming you have Sentry set up in your project
332 import * as Sentry from "@sentry/node"
333
334 const originalErrorHandler = errorHandler()
335
336 export default defineMiddlewares({
337 errorHandler: (
338 error: MedusaError | any,
339 req: MedusaRequest,
340 res: MedusaResponse,
341 next: MedusaNextFunction
342 ) => {
343 // for example, capture the error in Sentry
344 Sentry.captureException(error)
345 return originalErrorHandler(error, req, res, next)
346 },
347 })
348 ```
349
350 In this example, you import the `errorHandler` function from the Medusa Framework. Then, you call it to get the original error handler function.
351
352 Finally, you use it in your custom error handler after performing your custom logic, such as capturing the error in Sentry.