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.

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);
        })
fork icon339
star icon0
watch icon2

+ 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) {
fork icon259
star icon289
watch icon104

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.

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}.`))
        })
    )
}
fork icon45
star icon180
watch icon34

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)),
fork icon45
star icon178
watch icon34

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))
      }
    },
  },
])
fork icon41
star icon115
watch icon9

+ 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);
                })
        )
},
{
fork icon339
star icon0
watch icon2

+ 5 other calls in file

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
fork icon45
star icon178
watch icon34

+ 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(
fork icon9
star icon10
watch icon5

+ 11 other calls in file

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 =>
fork icon3
star icon6
watch icon4

+ 3 other calls in file

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;
fork icon299
star icon0
watch icon1

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;
fork icon85
star icon0
watch icon0

+ 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'),
fork icon29
star icon360
watch icon7

+ 3 other calls in file

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$);
}
fork icon0
star icon1
watch icon5

+ 3 other calls in file

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}` : ''}`)
            )
    )
)
fork icon45
star icon0
watch icon0

+ 3 other calls in file

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) => {
fork icon0
star icon2
watch icon3

+ 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);
    }
}));
fork icon0
star icon0
watch icon1

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'
fork icon0
star icon0
watch icon1

+ 2 other calls in file

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);
        }
fork icon0
star icon0
watch icon0

+ 23 other calls in file

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 )
    );
  }
}
fork icon0
star icon0
watch icon0

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);
fork icon0
star icon0
watch icon0