Strategies for capturing a module's thrown exception during loading process

Is there a way to validate environment variables and display an error message on the page if the environment is found to be invalid?

The config.ts file will throw an exception if the env variable is invalid.

import * as yup from 'yup'

console.log(process.env)

const envSchema = yup.object({
  REACT_APP_API_BASE_URL: yup
    .string()
    .required()
    .url()
    .label('REACT_APP_API_BASE_URL')
})

export default envSchema.validateSync(process.env)

The index.ts file is responsible for loading config.ts. Is it possible for it to catch any exceptions thrown by config.ts?

//try {  import cannot be inside try
import config from 'config' //exception thrown if env is invalid

Answer №1

If you utilize that particular syntax, it won't work as intended. However, there is a solution using dynamic imports that can achieve the desired outcome.

For more detailed examples and explanations regarding dynamic imports in TypeScript, you can visit .

In your specific scenario, the implementation would resemble the following:

const config = import('config').catch((error) => {
  // Handle errors here
});

It is important to note that this approach introduces asynchronous loading, meaning that config will represent a promise for the module value rather than the actual value itself. Consequently, the rest of your code will not automatically wait for the loading process to finish. You must explicitly use await config wherever its value is needed.

The reason the standard import syntax does not suffice is because it is designed to be extracted and executed statically before any code execution occurs, leaving no room for error handling setup.

Upon the release of TypeScript 3.7, you will have the option to employ top-level await in modules, enabling config to be treated as a conventional module value that subsequent code will naturally wait for:

const config = await import('config').catch((error) => {
  // Handle errors here
});

As a final alternative, if you are utilizing commonjs modules, you can resort to a synchronous require('config') call:

let config: any;
try {
  config = require('config');
} catch (e) {
  // Handle errors here
}

While this method delivers the expected outcome, it comes at the cost of type inference. It is advisable to transition towards ES modules rather than trying to work against them, given their standardized nature.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

External JavaScript files cannot be used with Angular 2

I am attempting to integrate the twitter-bootstrap-wizard JavaScript library into my Angular 2 project, but I keep encountering the following error: WEBPACK_MODULE_1_jquery(...).bootstrapWizard is not a function I have created a new Angular app using a ...

Improved ergonomics for enhancing TypeScript union-narrowing typeguard function

Within our codebase, we have a utility that generates a typeguard to narrow down a discriminated union: export type ExtractBranchFromUnion< UNION, DISCRIMINANT extends keyof UNION, BRANCH extends UNION[DISCRIMINANT], > = UNION extends Record< ...

ERROR UnhandledTypeError: Unable to access attributes of null (attempting to retrieve 'pipe')

When I include "{ observe: 'response' }" in my request, why do I encounter an error (ERROR TypeError: Cannot read properties of undefined (reading 'pipe'))? This is to retrieve all headers. let answer = this.http.post<ResponseLog ...

Using React with Typescript involves using the React.createElement method

I am facing an issue with a reference to a FunctionalComponent in my object. When I try to pass this reference into the createElement statement, it triggers a TypeScript error. Question: Why is this error occurring? Both Component and FunctionalComponent ...

What is the best way to select types conditionally based on the presence of a property in another type?

To begin with, I have a specific desired outcome: type Wrapper<ID extends string> = { id: ID }; type WrapperWithPayload<ID extends string, Payload> = { id: ID, payload: Payload }; enum IDs { FOO = "ID Foo", BAR = "ID Bar", BAZ = "ID Baz ...

What steps can be taken to resolve the error message "How can you repair 'Cannot read properties of undefined (reading 'front_default')'?"

I'm encountering an issue while trying to display data from an API. Although I am able to access the data, a perplexing error keeps popping up that I can't seem to troubleshoot. Here's the error message: Uncaught TypeError: Cannot read pr ...

Problem with (click) event not triggering in innerHtml content in Angular 4

For some reason, my function isn't triggered when I click the <a... tag. Inside my component, I have the following code: public htmlstr: string; public idUser:number; this.idUser = 1; this.htmlstr = `<a (click)="delete(idUser)">${idUser}&l ...

Retrieve a type from a Union by matching a string property

Looking at the following structure: type Invitation = | { __typename?: 'ClientInvitation' email: string hash: string organizationName: string } | { __typename?: 'ExpertInvitation' email: strin ...

In Vue 3, the v-model feature is utilized as parameter passing instead of using :prop and @emit

I've been trying to implement two-way binding using v-model in Vue.js based on this article. The idea is to pass values from a parent component to a child component with automatic event emission when the value changes in the child component. However, ...

What is the best way to include type within a nested object?

How should I properly define types for a nested object structured like the example below? const theme: DefaultTheme = { color: { primary: '#5039E7', secondary: '#372E4B', heading: '#4D5062', }, ...

Webpack 2.7.0 throws an error: "Unexpected parameter: theme"

At the moment, I am on webpack 1.16.0 and using --theme as an argument to set the output path and plugin paths. The command appears as: rimraf dist && webpack --bail --progress --profile --theme=<name of theme> However, as I try to upgrade ...

A step-by-step guide on incorporating MarkerClusterer into a google-map-react component

I am looking to integrate MarkerClusterer into my Google Map using a library or component. Here is a snippet of my current code. Can anyone provide guidance on how I can achieve this with the google-map-react library? Thank you. const handleApiLoaded = ({ ...

Utilize a single function across multiple React components to interact with the Redux store, promoting code reusability and

Currently facing a dilemma. Here is a snippet of code that updates data in the redux store from a function, and it functions smoothly without any issues. const handleCBLabelText = (position: string, text: string) => { dispatch({ type: ' ...

When I refresh the page in Angular2, the router parameters do not get loaded again

When loading my application on routers without parameters, everything is normal. However, when trying to use a router with params, the application fails to load. For example: localhost:3000/usersid/:id The code for the router is as follows: const appRou ...

How to handle an already initialised array in Angular?

I came across an interesting demo on exporting data to Excel using Angular 12. The demo can be found at the following link: This particular example utilizes an array within the component TypeScript file. import { Component } from '@angular/core' ...

import types dynamically in TypeScript

One of the files I have is called MyFactory.ts. Here is its content: export type CommandFactory = () => string[] | undefined; export enum FactoryIds {commandFactory : 'commandFactory'} Now, my goal is to dynamically import this file into anot ...

Exploring Child Types in Typescript and JSX minus the React framework

It seems like there's a missing piece of the puzzle that I can't quite figure out. Despite going through the documentation on JSX in non-React settings, I'm still unable to spot my mistake. Let's examine the following code: /** @jsx pra ...

Accessing information from an Odata controller in Angular2

Greetings as a first-time question asker and long-time reader/lurker. I've been delving into learning angular2, but I'm facing some challenges when it comes to retrieving data from an odata controller. In my simple Angular 2 application, I'm ...

Vue3 project encountering issues with Typescript integration

When I created a new application using Vue CLI (Vue3, Babel, Typescript), I encountered an issue where the 'config' object on the main app object returned from the createApp function was not accessible. In VS Code, I could see the Typescript &ap ...

Ways to create a versatile function for generating TypedArrays instances

I'm working on a function that looks like this: export function createTypedArray<T extends TypedArray>( arg : { source : T, arraySize : number } ) : T { if( arg.source instanceof Int32Array ) { return new Int32Array( arg.arraySize ); } ...