Created
April 5, 2024 20:21
-
-
Save matthewmorek/e8a60f6e52600ba97e1117883e985066 to your computer and use it in GitHub Desktop.
Next.js API Route Handler with error handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Represents an error that occurs when data fails to validate against the API's expected schema or requirements. | |
* This class extends the native JavaScript `Error` class, adding a `statusCode` property to facilitate API error handling. | |
* | |
* @example | |
* // Throws an APIValidationError with a custom message and a 400 Bad Request status code. | |
* throw new APIValidationError('Invalid user input', 400); | |
* | |
* @extends Error | |
*/ | |
export class APIValidationError extends Error { | |
/** | |
* The HTTP status code that should be returned to the client when this error occurs. | |
* | |
* @type {number} | |
*/ | |
statusCode: number | |
/** | |
* Creates an instance of APIValidationError. | |
* | |
* @param {string} message - The error message that describes the validation failure. | |
* @param {number} statusCode - The HTTP status code associated with this kind of validation error. | |
* Commonly used codes include 400 for Bad Request or 422 for Unprocessable Entity. | |
*/ | |
constructor(message: string, statusCode: number) { | |
super(message) | |
this.name = 'ValidationError' | |
this.statusCode = statusCode | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { APIValidationError } from './api-error' | |
// GET /api/blog/1234-whatever | |
export async function GET( | |
request: Request, | |
{ params }: { params: { id: string } } | |
) { | |
try { | |
if (params.id) { | |
return Response.json( | |
{ status: 'success', message: 'Vote Recorded' }, | |
{ status: 200 } | |
) | |
} else { | |
throw new APIValidationError('Invalid blogpost [id]', 410) | |
} | |
} catch (error) { | |
if (error instanceof APIValidationError) { | |
return Response.json( | |
{ status: 'error', message: error.message }, | |
{ status: error.statusCode } | |
) | |
} else { | |
return Response.json( | |
{ status: 'error', message: 'Unknown error occurred' }, | |
{ status: 500 } | |
) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment