@@ -183,198 +183,6 @@ app.get('/exmaple', (c) => {
183
183
| ` message ` | String | A string describing the nature of the error . | N / A |
184
184
| ` statusCode ` | Integer | An HTTP status code indicating the error ' s nature (e.g., 400, 401). | 500 |
185
185
186
-
187
- ## Contributing
188
-
189
- We welcome contributions from the community to enhance and improve the ` hono-error-handler ` package . If you ' d like to contribute, please follow these steps:
190
-
191
- 1. ** Fork the Repository :** Start by forking the [hono - error - handler repository ](https :// github.com/yourus# Hono Error Handler
192
-
193
- This is a custom error handler middleware for the [Hono ](https :// hono.dev/) web framework.
194
- It allows you to define and use your own error handling functions while providing some default error
195
- handling behavior .
196
-
197
- ## Installation
198
-
199
- You can install the package with :
200
-
201
- ` ` ` bash
202
- npm install hono-error-handler
203
- yarn add hono-error-handler
204
- bun install hono-error-handler
205
- ` ` `
206
-
207
- ## Usage
208
-
209
- Simplify error handling in your JSON API applications with the ` hono-error-handler ` package .
210
- This package streamlines error management within your route handlers by providing an easy way to
211
- create custom errors with associated status codes using ` ErrorResponse ` . By using the ` errorHandler ` , you can eliminate the need for extensive try - catch blocks in your routes , resulting in
212
- cleaner and more maintainable code . Additionally , the ` errorHandler ` ensures consistent error responses
213
- in JSON format across your application . If you need to throw errors in your routes ,
214
- ` ErrorResponse ` simplifies the process . Without any custom error handlers defined ,
215
- the default behavior is to return a 500 Internal Server Error response in JSON .
216
-
217
- ### Create Error Handlers
218
-
219
- ** Syntax ** : The function is defined as follows:
220
- ```ts
221
- const handleMongooseErrors = (error : CustomErrorHandler ) => {
222
- // Error handling logic here
223
- };
224
- ` ` `
225
- > (error: CustomErrorHandler) => declares an arrow function that takes one parameter named error,
226
- which is of type CustomErrorHandler.
227
-
228
- - **Parameter (error: CustomErrorHandler)**:
229
- The error parameter represents an error object that is expected to conform to the
230
- CustomErrorHandler interface. This error will be passed to your function automatically.
231
-
232
-
233
- - **Using If Statements**: Inside the function, there are multiple if statements that check for specific
234
- conditions related to your error types. These conditions are used to identify and handle
235
- different error scenarios.
236
-
237
-
238
- - **Return**: When a specific condition is met, the function modifies the error object to provide a more
239
- informative error message and sets an appropriate status code. For example:
240
-
241
- ` ` ` ts
242
- // Mongoose bad ObjectId
243
- if (error .name === ' CastError' ) {
244
- error.message = ' Resource not found' ;
245
- error.statusCode = 400 ;
246
- return error;
247
- }
248
- ` ` `
249
- > In this case, if the error's ` name ` property matches 'CastError', the function updates the
250
- ` error ` object's message and ` statusCode ` properties and immediately returns the modified ` error ` object.
251
-
252
- - **Default Return**: At the end of the function, there's a default return statement:
253
-
254
- ` ` ` ts
255
- return error ;
256
- ` ` `
257
-
258
- > This default return ensures that if none of the specific conditions are met
259
- (i.e., the error doesn't match any known Mongoose error type), the original ` error ` object is
260
- returned without modification.
261
-
262
- Here is a full example of a custom error handler with mongoose:
263
-
264
- ` ` ` ts
265
- import { CustomErrorHandler } from ' hono-error-handler' ;
266
-
267
- const handleMongooseErrors = (error : CustomErrorHandler ) => {
268
- // Mongoose bad ObjectId
269
- if (error .name === ' CastError' ) {
270
- error .message = ' Resource not found' ;
271
- error .statusCode = 400 ;
272
- return error ;
273
- }
274
-
275
- // Mongoose duplicate key
276
- if (error .code === 11000 ) {
277
- const field = Object .keys (error .keyValue )[0 ];
278
- error .message = ` ${field } is already registered ` ;
279
- error .statusCode = 400 ;
280
- return error ;
281
- }
282
-
283
- // Mongoose validation error
284
- if (error .name === ' ValidationError' ) {
285
- let message = ' ' ;
286
- Object .values (error .errors ).map ((val : any ) => {
287
- message += ` ${val .message }, ` ;
288
- });
289
- error .message = message ;
290
- error .statusCode = 400 ;
291
- return error ;
292
- }
293
-
294
- return error ;
295
- };
296
-
297
- export default handleMongooseErrors ;
298
- ` ` `
299
-
300
- ### Adding The Error Handler To Your App
301
-
302
- Import the error handler
303
-
304
- ` ` ` ts
305
- import { errorHandler } from ' hono-error-handler' ;
306
- ` ` ` `
307
-
308
-
309
-
310
- Import your custom error handler function :
311
-
312
- ```ts
313
- import handleMongooseErrors from './handleMongooseErrors';
314
- ` ` `
315
-
316
- Create an array of your custom error handlers.
317
- This array will be passed to the errorHandler function.
318
-
319
- ` ` ` ts
320
- const errorHandlers = [handleMongooseErrors , additionalErrorhander ];
321
-
322
- ` ` `
323
-
324
- Set up the error handler for your app. Pass in the ` errorHandlers ` array as the first argument to
325
- ` errorHandler ` . You can also specify whether to print error stacks to the console
326
- (optional, default is true) as the second argument.
327
-
328
- ` ` ` ts
329
- app .onError (errorHandler (errorHandlers , false ));
330
- ` ` `
331
- ### Throwing Custom Errors In Routes
332
-
333
- Import the ` ErrorResponse ` class:
334
-
335
- ` ` ` ts
336
- import { ErrorResponse } from ' hono-error-handler' ;
337
- ` ` `
338
-
339
- In your route handler, when you encounter a condition that should result in an error response,
340
- create a new instance of ErrorResponse. Provide the error message and status code as arguments to
341
- the constructor. For example:
342
-
343
- ` ` ` ts
344
- app .get (' /exmaple' , (c ) => {
345
- // Check some condition
346
- if (someConditionIsNotMet ) {
347
- // Throw a custom error using ErrorResponse
348
- throw new ErrorResponse (' Resource not found' , 404 );
349
- }
350
-
351
- // Your regular route logic
352
- // ...
353
- });
354
- ` ` `
355
-
356
- > This will bypass the ` errorHandler ` and immediately send the response
357
-
358
-
359
- ## Parameters
360
-
361
- ## Parameters
362
-
363
- ### ` errorHandler ` Parameters
364
-
365
- | Parameter | Type | Description | Default |
366
- |-----------------|--------------------|-----------------------------------------------------------------------------------------------------------------|---------|
367
- | ` errorHandlers ` | Array of Functions | An array of custom error handlers that modify error objects based on specific error conditions. | [] |
368
- | ` printStack ` | Optional Boolean | A boolean flag that determines whether to print the stack trace of the error to the console. Default is ` true ` . | ` true ` |
369
-
370
- ### ` ErrorResponse ` Parameters
371
-
372
- | Parameter | Type | Description | Default |
373
- |--------------|---------|---------------------------------------------------------------------|---------|
374
- | ` message ` | String | A string describing the nature of the error. | N/A |
375
- | ` statusCode ` | Integer | An HTTP status code indicating the error's nature (e.g., 400, 401). | 500 |
376
-
377
-
378
186
## Contributing
379
187
380
188
We welcome contributions from the community to enhance and improve the ` hono-error-handler ` package . If you ' d like to contribute, please follow these steps:
0 commit comments