Last active
March 17, 2020 13:51
-
-
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)
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 { 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) | |
})) | |
} |
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 { 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