Skip to content

Commit

Permalink
Show Micro.blog error message when available
Browse files Browse the repository at this point in the history
  • Loading branch information
otaviocc committed Jun 5, 2024
1 parent 7acb3db commit 8621c1e
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
34 changes: 34 additions & 0 deletions src/networking/ErrorFactory.ts
Original file line number Diff line number Diff line change
@@ -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<Error> {
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)
}
}
3 changes: 2 additions & 1 deletion src/networking/NetworkClient.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { ErrorFactory } from '@networking/ErrorFactory'
import { NetworkRequest } from '@networking/NetworkRequest'

export interface NetworkClientInterface {
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 8621c1e

Please sign in to comment.