Skip to content

Commit

Permalink
Merge pull request #36 from labd/errorHandling
Browse files Browse the repository at this point in the history
chore: custom errors
  • Loading branch information
BramKaashoek authored Jun 11, 2024
2 parents 0476b44 + fcb7f10 commit b360423
Show file tree
Hide file tree
Showing 6 changed files with 103 additions and 15 deletions.
5 changes: 5 additions & 0 deletions .changeset/two-jeans-kick.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"react-loqate": major
---

Breaking: implement LoqateError and ReactLoqateError
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,15 @@ import AddressSearch from 'react-loqate';
/>;
```

### Errors

Two types of errors can be thrown, LoqateError and ReactLoqateError.
Loqate Errors are errors from the Loqate API. Their structure, causes and resolutions can be [found in the loqate docs](https://www.loqate.com/developers/api/generic-errors/).

Currently only one ReactLoqateError can be thrown. This error occurs when the Retrieve API returns an empty Items array after querying it with an existing ID.

It is on you as the implementing party to catch and handle these errors.

### Contributing

This codebases use [@changesets](https://github.com/changesets/changesets) for release and version management
Expand Down
41 changes: 41 additions & 0 deletions src/error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
type ReactLocateErrorCode = 'NO_ITEMS_RETRIEVED';

export class ReactLoqateError extends Error {
public code: ReactLocateErrorCode;

constructor({
message,
code,
}: {
message: string;
code: ReactLocateErrorCode;
}) {
super(message);
this.code = code;
}
}

export class LoqateError extends Error {
public Cause: string;
public Description: string;
public Error: string;
public Resolution: string;

constructor({
Description,
Cause,
Error,
Resolution,
}: {
Description: string;
Cause: string;
Error: string;
Resolution: string;
}) {
super(Description);
this.Cause = Cause;
this.Description = Description;
this.Error = Error;
this.Resolution = Resolution;
}
}
7 changes: 2 additions & 5 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ export interface Item {
Highlight: string;
}

export interface ErrorItem {
export interface LoqateErrorItem {
Error: string;
Description: string;
Cause: string;
Expand Down Expand Up @@ -172,16 +172,13 @@ function AddressSearch(props: Props): JSX.Element {
Items = res.Items;
}
} catch (e) {
setSuggestions([]);
// error needs to be thrown in the render in order to be caught by the ErrorBoundary
setError(() => {
throw e;
});
}

if (Items.length) {
setSuggestions([]);
}

onSelect(Items[0] as unknown as Address);
return;
}
Expand Down
20 changes: 15 additions & 5 deletions src/utils/Loqate.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { ErrorItem, Item } from '..';
import { Item, LoqateErrorItem } from '..';
import {
LOQATE_BASE_URL,
LOQATE_FIND_URL,
LOQATE_RETRIEVE_URL,
} from '../constants/loqate';
import { LoqateError, ReactLoqateError } from '../error';

interface FindQuery {
text: string;
Expand All @@ -13,7 +14,7 @@ interface FindQuery {
containerId?: string;
}

type LoqateResponse = { Items?: Item[] | ErrorItem[] };
type LoqateResponse = { Items?: Item[] | LoqateErrorItem[] };
type LoqateNoErrorResponse = { Items?: Item[] };
class Loqate {
constructor(
Expand All @@ -29,7 +30,16 @@ class Loqate {
const params = new URLSearchParams({ Id: id, Key: this.key });
const url = `${this.baseUrl}/${LOQATE_RETRIEVE_URL}?${params.toString()}`;
const res = await fetch(url).then<LoqateResponse>((r) => r.json());
return this.handleErrors(res);
const noLoqateErrosRes = this.handleErrors(res);

if (noLoqateErrosRes.Items && !noLoqateErrosRes.Items?.length) {
throw new ReactLoqateError({
code: 'NO_ITEMS_RETRIEVED',
message: `Loqate retrieve API did not return any address items for the provided ID ${id}`,
});
}

return noLoqateErrosRes;
}

public async find(query: FindQuery): Promise<LoqateNoErrorResponse> {
Expand All @@ -54,9 +64,9 @@ class Loqate {
}

private handleErrors = (res: LoqateResponse): LoqateNoErrorResponse => {
const firstItem: Item | ErrorItem | undefined = res?.Items?.[0];
const firstItem: Item | LoqateErrorItem | undefined = res?.Items?.[0];
if (firstItem && Object.hasOwn(firstItem, 'Error')) {
throw new Error(`Loqate error: ${JSON.stringify(firstItem)}`);
throw new LoqateError(firstItem as LoqateErrorItem);
}

return res as LoqateNoErrorResponse;
Expand Down
36 changes: 31 additions & 5 deletions src/utils/__tests__/Loqate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ describe('Loqate', () => {
expect({ Items }).toEqual(suggestions);
});

it('should throw loqate errors', async () => {
it('should throw errors', async () => {
server.use(errorHandler);

const loqate = Loqate.create('some-key');
Expand All @@ -54,10 +54,36 @@ describe('Loqate', () => {
limit: 10,
containerId: 'some-container-id',
});
}).rejects.toThrowError(
new Error(
'Loqate error: {"Error":"2","Description":"Unknown key","Cause":"The key you are using to access the service was not found.","Resolution":"Please check that the key is correct. It should be in the form AA11-AA11-AA11-AA11."}'
)
}).rejects.toThrowError(new Error('Unknown key'));
});

it('should throw loqate errors', async () => {
server.use(errorHandler);

const loqate = Loqate.create('some-key');

let error;
try {
await loqate.find({
text: 'some-text',
language: 'some-language',
countries: ['GB', 'US'],
limit: 10,
containerId: 'some-container-id',
});
} catch (e) {
error = e;
}

expect(error).toEqual(new Error('Unknown key'));
expect(JSON.stringify(error)).toEqual(
JSON.stringify({
Cause: 'The key you are using to access the service was not found.',
Description: 'Unknown key',
Error: '2',
Resolution:
'Please check that the key is correct. It should be in the form AA11-AA11-AA11-AA11.',
})
);
});
});
Expand Down

0 comments on commit b360423

Please sign in to comment.