Skip to content

Instantly share code, notes, and snippets.

@nilsmehlhorn
Last active March 17, 2020 13:51
Show Gist options
  • Save nilsmehlhorn/14e2edb545088ea741784e122e77ad20 to your computer and use it in GitHub Desktop.
Save nilsmehlhorn/14e2edb545088ea741784e122e77ad20 to your computer and use it in GitHub Desktop.
RxJS operator for throwing semantic errors for certain HTTP status codes (now part of ngx-operators)
import { Observable, throwError } from 'rxjs'
import { catchError } from 'rxjs/operators'
import { HttpErrorResponse } from '@angular/common/http'
export const throwForCodes = (codeErrors: Array<[number, () => Error]>) => {
const mappedCodeErrors = new Map(codeErrors)
return <T>(source: Observable<T>) =>
source.pipe(catchError(error => {
if (error instanceof HttpErrorResponse) {
const mappedErrorFn = mappedCodeErrors.get(error.status)
return throwError(mappedErrorFn ? mappedErrorFn() : error)
}
return throwError(error)
}))
}
import { throwForCodes } from './throw-for-codes';
import { HttpErrorResponse } from '@angular/common/http'
import { NOT_FOUND, CONFLICT } from 'http-status-codes'
import { throwError } from 'rxjs'
describe('throwForCodes', () => {
it('should rethrow mapped error', done => {
const httpError = new HttpErrorResponse({status: NOT_FOUND})
const message = 'User not found'
throwError(httpError).pipe(throwForCodes([
[NOT_FOUND, () => new Error(message)]
]))
.subscribe(
() => fail(),
err => {
expect(err.message).toEqual(message)
done()
}
)
});
it('should rethrow original error for unmapped errors', done => {
const httpError = new HttpErrorResponse({status: CONFLICT})
const message = 'User not found'
throwError(httpError).pipe(throwForCodes([
[NOT_FOUND, () => new Error(message)]
]))
.subscribe(
() => fail(),
err => {
expect(err).toEqual(httpError)
done()
}
)
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment