diff --git a/src/networking/ErrorFactory.ts b/src/networking/ErrorFactory.ts new file mode 100644 index 0000000..71ccd6e --- /dev/null +++ b/src/networking/ErrorFactory.ts @@ -0,0 +1,34 @@ +/* + * Factory responsible for creating Errors from network responses. + */ +export class ErrorFactory { + + // The Micropub specification defines response errors as: + // + // { + // "error": "invalid_request", + // "error_description": "The post with the requested URL was not found" + // } + // + // This method is responsible for building an Error instance with the + // information contained in the response error (if any). + public static async makeErrorFromResponse( + response: Response + ): Promise { + let errorDetails = '' + + const errorResponse = await response.json() + const hasError = errorResponse.error + const hasDescription = errorResponse.error_description + + if (hasError && hasDescription) { + errorDetails = errorResponse.error_description + } else if (hasError) { + errorDetails = 'Micro.blog error code: ' + errorResponse.error + } else { + errorDetails = 'Network error: ' + response.status + } + + return new Error(errorDetails) + } +} diff --git a/src/networking/NetworkClient.ts b/src/networking/NetworkClient.ts index 6fc9e46..351fecb 100644 --- a/src/networking/NetworkClient.ts +++ b/src/networking/NetworkClient.ts @@ -1,3 +1,4 @@ +import { ErrorFactory } from '@networking/ErrorFactory' import { NetworkRequest } from '@networking/NetworkRequest' export interface NetworkClientInterface { @@ -45,7 +46,7 @@ export class NetworkClient implements NetworkClientInterface { }) if (!response.ok) { - throw new Error('Network error: ' + response.status) + throw await ErrorFactory.makeErrorFromResponse(response) } const isSuccess = response.status >= 200 && response.status < 300