How to use the throwError function from rxjs
Find comprehensive JavaScript rxjs.throwError code examples handpicked from public code repositorys.
rxjs.throwError is a function that creates an Observable that immediately emits an error and terminates.
GitHub: MunifTanjim/np
119 120 121 122 123 124 125 126 127 128
title: 'Installing dependencies using Yarn', enabled: () => options.yarn === true, task: () => exec('yarn', ['install', '--frozen-lockfile', '--production=false']).pipe( catchError(error => { if (error.stderr.startsWith('error Your lockfile needs to be updated')) { return throwError(new Error('yarn.lock file is outdated. Run yarn, commit the updated lockfile and try again.')); } return throwError(error); })
+ 5 other calls in file
172 173 174 175 176 177 178 179 180 181
if (tenant.name === tenantName) { logger.info(`Aps: has default tenantId: ${tenantId} and name ${tenantName}`); return true; } else { logger.info(`Wrong configuration. Another tenant has been created with id ${tenant.id} and name ${tenant.name}`); throwError(`Wrong configuration. Another tenant has been created with id ${tenant.id} and name ${tenant.name}`); } } async function createDefaultTenant(tenantName) {
How does rxjs.throwError work?
Sure! rxjs.throwError is a function that creates an Observable that immediately emits an error and terminates. When you call rxjs.throwError with an error object or a string, it creates an Observable that will emit that error and immediately terminate. This is useful when you want to create an Observable that always fails, such as when a required resource is unavailable or an input validation check fails. You can subscribe to the Observable returned by rxjs.throwError just like any other Observable. When you subscribe, the error callback in the observer will be called with the error object or string that you passed to rxjs.throwError. If you don't provide an error object or string to rxjs.throwError, it will throw a TypeError. If you want to catch the error, you can use the standard try...catch construct or the catchError operator on the Observable.
GitHub: openforis/sepal
41 42 43 44 45 46 47 48 49
else if (stream === 'stderr') log.warn(msg(`stderr\n${value}`)) }), catchError(error => { log.error(msg(error)) return throwError(() => new Error(`Failed to ${description}.`)) }) ) }
GitHub: openforis/sepal
45 46 47 48 49 50 51 52 53 54
const monitor$ = taskId => interval(MONITORING_FREQUENCY).pipe( exhaustMap(() => status$(taskId)), switchMap(({state, error_message: error}) => (error || state === FAILED) ? throwError(() => new Error(error)) : of(state) ), distinctUntilChanged(), takeWhile(state => isRunning(state)),
Ai Example
1 2 3 4 5 6 7 8 9 10
const { throwError } = require("rxjs"); const source = throwError("Oops! Something went wrong."); const subscription = source.subscribe({ next: () => console.log("This should not be called."), error: (err) => console.error(err), complete: () => console.log("This should not be called."), }); // Output: "Oops! Something went wrong."
In this example, we first import throwError from the rxjs library. We then create an Observable source using throwError('Oops! Something went wrong.'), which emits an error message and immediately terminates. We subscribe to this Observable and provide three callbacks to handle the different events that can occur: next, error, and complete. Since source emits an error and terminates immediately, the next and complete callbacks will never be called. Instead, the error callback will be called with the error message 'Oops! Something went wrong.'. We log this error message to the console using console.error().
156 157 158 159 160 161 162 163 164 165
const scriptFilename = path.join(pluginPath, 'script.js') if (await scriptGrep.existsInFile(scriptFilename, 'FetchMock')) { const error = `Fetch Mocks are not allowed in the script.js file during releases. Please remove it and try again.` print.error(error) process.exit() // return throwError(new Error(error)) } }, }, ])
+ 5 other calls in file
83 84 85 86 87 88 89 90 91 92
catchError(error => { if (error.stderr.startsWith('error Your lockfile needs to be updated')) { throwError(new Error('yarn.lock file is outdated. Run yarn, commit the updated lockfile and try again.')); } throwError(error); }) ) }, {
+ 5 other calls in file
GitHub: openforis/sepal
74 75 76 77 78 79 80 81 82 83
.join('&') const validateResponse = (response, validStatuses) => !validStatuses || validStatuses.includes(response.statusCode) ? response : throwError(() => response) const execute$ = (url, method, {retries, query, username, password, headers, validStatuses, ...args}) => { const queryString = toQueryString(query) const urlWithQuery = queryString ? `${url}?${queryString}` : url
+ 5 other calls in file
49 50 51 52 53 54 55 56 57 58
observer.next(4); }).pipe( retryWhen(errors => errors.pipe( delay(1000), take(retryAttempts), concat( throwError('ensure our retry crashes instead of completes')) )) ); retryWhenStream$.subscribe(
+ 11 other calls in file
GitHub: rxjskr/book-examples
21 22 23 24 25 26 27 28 29 30
}, { count: 0 } ), mergeMap(errorInfo => { if (errorInfo.count === n + 1) { return throwError(errorInfo.error); } return of(errorInfo); }), tap(errorInfo =>
+ 3 other calls in file
GitHub: caosbad/api
61 62 63 64 65 66 67 68 69 70
exports.onErrorResumeNext = rxjs.onErrorResumeNext; exports.pairs = rxjs.pairs; exports.partition = rxjs.partition; exports.race = rxjs.race; exports.range = rxjs.range; exports.throwError = rxjs.throwError; exports.timer = rxjs.timer; exports.using = rxjs.using; exports.zip = rxjs.zip; exports.scheduled = rxjs.scheduled;
GitHub: jeffbski/wait-on
126 127 128 129 130 131 132 133 134
const timeoutError$ = timeout !== Infinity ? timer(timeout).pipe( mergeMap(() => { const resourcesWaitingFor = determineRemainingResources(resources, lastResourcesState).join(', '); return throwError(Error(`${TIMEOUT_ERR_MSG}: ${resourcesWaitingFor}`)); }) ) : NEVER;
+ 7 other calls in file
53 54 55 56 57 58 59 60 61 62
mockSettingsService.getLastSynchronizationDate.mockReturnValue( new Date('1970-01-01'), ); mockFlathubSynchronizer.startSynchronization.mockReturnValueOnce( throwError('err'), ); mockAppImageHubSynchronizer.startSynchronization.mockReturnValueOnce( throwError('err'),
+ 3 other calls in file
GitHub: hatchapp/game-server
52 53 54 55 56 57 58 59 60 61
* @returns {Observable<*>} */ function createRingMoveStream(ring){ const move$ = fromEvent(ring, 'move'); const err$ = fromEvent(ring, 'error').pipe( mergeMap((err) => throwError(err)) ); return merge(move$, err$); }
+ 3 other calls in file
GitHub: VEGMQAZ/sepal
119 120 121 122 123 124 125 126 127 128
}) ).pipe( switchMap(({files}) => files.length ? of({id: files[0].id}) // handling the first match only : throwError( () => new NotFoundException(`Directory "${name}" not found ${parentId ? `in parent ${parentId}` : ''}`) ) ) )
+ 3 other calls in file
GitHub: lbovet/makine
20 21 22 23 24 25 26 27 28 29
} const onErrorMap = (pattern, project) => catchError(err => err.statusCode && err.statusCode.toString().match(pattern) ? project(err) : throwError(err) ) return { on: (method, url) => (...pipeline) => {
+ 9 other calls in file
217 218 219 220 221 222 223 224 225 226
else { try { fs.unlinkSync(src_1.getSystemPath(path)); } catch (err) { return rxjs_1.throwError(err); } return rxjs_1.of(undefined); } }));
129 130 131 132 133 134 135 136 137 138
timer: 1000, width: '500px' }); }; ApiService.prototype.formatErrors = function (error) { return rxjs_1.throwError(error.error); }; ApiService = __decorate([ core_1.Injectable({ providedIn: 'root'
+ 2 other calls in file
GitHub: saleem1989/SalotimeMini
67 68 69 70 71 72 73 74 75 76
case 'delete': return host.delete(record.path); case 'rename': return host.rename(record.from, record.to); case 'create': return host.exists(record.path).pipe(operators_1.switchMap(exists => { if (exists && !force) { return rxjs_1.throwError(new exception_1.FileAlreadyExistException(record.path)); } else { return host.write(record.path, record.content); }
+ 23 other calls in file
GitHub: nebulae-tpi/ms-sales
333 334 335 336 337 338 339 340 341 342
* Creates a custom error observable * @param {*} error Error * @param {*} methodError Method where the error was generated */ createCustomError$(error, methodError) { return throwError( new CustomError("POS CQRS", methodError || "", error.code, error.description ) ); } }
56 57 58 59 60 61 62 63 64 65
console.error('An error occurred:', error.error); } else { console.error("Backend returned code " + error.status + ", body was: ", error.error); } return rxjs_1.throwError(function () { return new Error('Something bad happened; please try again later.'); }); }; GetDataService = __decorate([ core_1.Injectable() ], GetDataService);