I recently got that curious exception in my Xamarin App on iOS. I currently struggle to symbolicate it properly in HockeyApp but anyway here is the crash reporter log from HA:
Hardware Model: iPhone4,1
Process: trucker_rolspedi [625]
Path: /var/containers/Bundle/Application/B028371C-62B4-4BCD-8491-C78EFE825D22/trucker_rolspediOS.app/trucker_rolspediOS
Identifier: com.rolsped.TruckerApp
Version: 1.1 (60)
Code Type: ARM
Parent Process: ??? [1]
Date/Time: 2016-12-04T04:53:09Z
Launch Time: 2016-12-04T04:46:07Z
OS Version: iPhone OS 9.3.5 (13G36)
Report Version: 104-Xamarin
Exception Type: SIGABRT
Exception Codes: #0 at 0x21efec5c
Crashed Thread: 0
Application Specific Information:
*** Terminating app due to uncaught exception 'System.ArgumentOutOfRangeException', reason: 'System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.'
Xamarin Exception Stack:
Parameter name: index
at System.ThrowHelper.ThrowArgumentOutOfRangeException (System.ExceptionArgument argument, System.ExceptionResource resource) <0x384df0 + 0x00040> in <15e850188d9f425bbeae90f0bbc51e17#ddbdd0f52c53581cb2d9c691bfe34183>:0
at System.ThrowHelper.ThrowArgumentOutOfRangeException () <0x384b68 + 0x0001b> in <15e850188d9f425bbeae90f0bbc51e17#ddbdd0f52c53581cb2d9c691bfe34183>:0
at System.Collections.Generic.List`1[T].get_Item (System.Int32 index) <0x24a68c + 0x0002f> in <15e850188d9f425bbeae90f0bbc51e17#ddbdd0f52c53581cb2d9c691bfe34183>:0
at Xamarin.Forms.NavigationProxy.Pop () <0x5678b4 + 0x00047> in <f9095492ed2b43559d0236ac22ab7223#ddbdd0f52c53581cb2d9c691bfe34183>:0
at Xamarin.Forms.NavigationProxy.OnPopAsync (System.Boolean animated) <0x567518 + 0x0005b> in <f9095492ed2b43559d0236ac22ab7223#ddbdd0f52c53581cb2d9c691bfe34183>:0
at Xamarin.Forms.NavigationProxy.PopAsync (System.Boolean animated) <0x56708c + 0x0002f> in <f9095492ed2b43559d0236ac22ab7223#ddbdd0f52c53581cb2d9c691bfe34183>:0
at trucker_rolsped.Pages.Media.TaskPhotoUploadPage+<SendMediaOnClicked>d__9.MoveNext () <0xe86944 + 0x013bf> in <3fbc044b4d76429b8dee1ec91e769c22#ddbdd0f52c53581cb2d9c691bfe34183>:0
Here the Code from the root cause Stacktrace line. It must happen at the await Navigation.PopAsync(animated: false)statement:
private async void SendMediaOnClicked(object sender, EventArgs e)
{
SendMedia.IsEnabled = false;
try
{
SelectedMedia.DokArt = _dokArt;
SelectedMedia.TruckAppId = _truckAppId;
UserDialogs.Instance.ShowLoading("Foto wird hochgeladen...");
await AzureBlobStorageManager.Instance.UploadMediaAsync(SelectedMedia);
UserDialogs.Instance.HideLoading();
switch (SelectedMedia.MediaState)
{
case MediaState.Uploaded:
if (IsTakenPhoto)
{
var result = await DisplayAlert("Foto Upload", "Foto wurde erfolgreich hochgeladen. Möchten Sie das Foto jetzt vom Handy löschen?", "Ja", "Nein");
if (result)
{
//Platform specific file delete
var truckerappMedia = SelectedMedia.File.Path;
var platformFileHandler = DependencyService.Get<IFileHandling>();
if (platformFileHandler != null)
if (await platformFileHandler.FileExistsAsync(truckerappMedia))
{
var deleted = await platformFileHandler.DeleteFileAsync(truckerappMedia);
if (deleted)
UserDialogs.Instance.Toast("Foto wurde erfolgreich hochgeladen und am Handy gelöscht!!", TimeSpan.FromSeconds(value: 2));
else
UserDialogs.Instance.Toast("Foto konnte nicht gelöscht werden! Falls Sie das Foto nicht benötigen " +
"bitte in der Fotogallery selbst löschen", TimeSpan.FromSeconds(value: 5));
}
}
}
else
UserDialogs.Instance.Toast("Upload erfolgreich!", TimeSpan.FromSeconds(value: 2));
break;
case MediaState.Queued:
UserDialogs.Instance.Toast("Upload erfolgt automatisch wenn Sie wieder mit Internet oder dem mobilem Netz verbunden sind!");
break;
case MediaState.Created:
await DisplayAlert("Media Info", "Upload MediaState.Created!", "Ok");
break;
case MediaState.Error:
await DisplayAlert("Media Info", "Upload MediaState.Error!", "Ok");
break;
default:
await DisplayAlert("Media Info", "Upload MediaState Unknown!", "Ok");
break;
}
}
catch (Exception ex)
{
SelectedMedia.MediaState = MediaState.Error;
await DisplayAlert("Sende Media Fehler", ex.Message, "Ok");
}
finally
{
if (SelectedMedia.MediaState == MediaState.Uploaded)
{
SelectedMedia?.Dispose();
SelectedMedia = null;
}
_workflowItem.TruckAuftragWorkFlow.TaskStatusId = 80;
await Navigation.PopAsync(animated: false);
_tcs.SetResult(true);
}
}
Here the 2 code areas where I instantiate and use the TakePhotoUploadPage:
1. Usage: From another page called Task40ActionPage
In **Task40ActionPage ** I invoke that method to show the TakePhotoUploadPage :
private async void RejectLoadInTimeClicked(object sender, EventArgs e)
{
_workflowItem.TruckAuftragLauf.FlagFotoLadezeit = null;
try
{
await ShowPhotoPageAsync(this, _workflowItem);
}
catch (Exception ex)
{
await MetricsManagerHelper.Instance.SendExceptionToApplicationInsights(ex);
}
await Navigation.PopAsync(animated: false);
_tcs.SetResult(true);
}
public async Task<bool> ShowPhotoPageAsync(Page page, WorkflowItem workflowItem)
{
TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
try
{
await Navigation.PushAsync(new TaskPhotoUploadPage(tcs, workflowItem, dokArt: "50"), animated: false);
}
catch (Exception e)
{
tcs.SetException(e);
}
return await tcs.Task;
}
2. Usage: From an ICommand Action delegate:
public async Task Task50ActionAsync(WorkflowItem workflowItem)
{
bool isLastWorkItem = false;
var page = Application.Current.MainPage.Navigation.NavigationStack.LastOrDefault();
try
{
if (workflowItem.QuestionYn)
{
if (page != null)
Device.BeginInvokeOnMainThread(
async () =>
{
try
{
bool isOk = await page.DisplayAlert("Todo Command", "Task50ActionAsync ausführen?", "Ja", "Nein");
if (isOk)
{
await ShowPhotoPageAsync(page, workflowItem, dokArt: "60");
UserDialogs.Instance.ShowLoading("Aufgabe wird gespeichert...", MaskType.Black);
isLastWorkItem = await InnerTask50ActionAsync(workflowItem);
//PUSH changes to remote.db
await OfflineSyncStoreManager.Instance.PushAsync(OfflineSyncStoreManager.Instance.TruckAuftragWorkFlowTable.TableName);
if (isLastWorkItem)
{
// Set TAL to completed
workflowItem.TruckAuftragLauf.IsCompleted = true;
// Pop Workflow UI View
Device.BeginInvokeOnMainThread(async () => await page.Navigation.PopAsync(animated: false));
}
UserDialogs.Instance.HideLoading();
}
}
catch (Exception e)
{
await MetricsManagerHelper.Instance.SendExceptionToApplicationInsights(e);
Device.BeginInvokeOnMainThread(
async () =>
{
await
page.DisplayAlert("Todo Command Error",
$"TaskId={workflowItem.TaskId} Action Error:{e}", "Ok");
});
}
});
}
else
{
await ShowPhotoPageAsync(page, workflowItem, dokArt: "60");
UserDialogs.Instance.ShowLoading("Aufgabe wird gespeichert...", MaskType.Black);
isLastWorkItem = await InnerTask50ActionAsync(workflowItem);
//PUSH changes to remote.db
await OfflineSyncStoreManager.Instance.PushAsync(OfflineSyncStoreManager.Instance.TruckAuftragWorkFlowTable.TableName);
if (isLastWorkItem)
{
// Set TAL to completed
workflowItem.TruckAuftragLauf.IsCompleted = true;
// Pop Workflow UI View
Device.BeginInvokeOnMainThread(async () => await page.Navigation.PopAsync(animated: false));
}
UserDialogs.Instance.HideLoading();
}
}
catch (Exception e)
{
await MetricsManagerHelper.Instance.SendExceptionToApplicationInsights(e);
if (page != null)
Device.BeginInvokeOnMainThread(
async () =>
{
await
page.DisplayAlert("Todo Command Error", $"TaskId={workflowItem.TaskId} Action Error:{e}",
"Ok");
});
}
}
public async Task<bool> ShowPhotoPageAsync(Page page, WorkflowItem workflowItem, string dokArt)
{
TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
try
{
await page.Navigation.PushAsync(new TaskPhotoUploadPage(tcs, workflowItem, dokArt: dokArt), animated: false);
}
catch (Exception e)
{
tcs.SetException(e);
}
return await tcs.Task;
}
Thanks to everyone with helpful suggestions in advance,
Eric
As Yuri S. suggested that code works to fix a NavigationStack PopAsync when the Stack is empty:
if (Navigation.NavigationStack.Count == 1)
{
await MetricsManagerHelper.Instance.SendErrorToApplicationInsightsAsync($"Navigationstack Count == 1");
}
else
{
await Navigation.PopAsync(animated: false);
}
Thanks for you great support!!!
Eric
Related
E/App: Got error:
java.lang.IllegalArgumentException: Invalid Setup Intent client secret: pi_3LtYhHAZTS98jCaY3NVtpCAW_secret_yUvzN3ytPIexEVJGtOzvQCSOM
at com.stripe.android.model.SetupIntent$ClientSecret.
Here i added my all codes of java class and php api for the test but i got this above error on the same code so plz do my help
paymentSheet = new PaymentSheet(this, this::onPaymentSheetResult);
Fuel.INSTANCE.post("my api link",null).responseString(new Handler<String>() {
#Override
public void success(String s) {
try {
final JSONObject result = new JSONObject(s);
customerConfig = new PaymentSheet.CustomerConfiguration(
result.getString("customer"),
result.getString("ephemeralKey")
);
paymentIntentClientSecret = result.getString("paymentIntent");
PaymentConfiguration.init(getContext().getApplicationContext(), result.getString("publishableKey"));
} catch (JSONException e) { /* handle error */ }
}
#Override
public void failure(#NotNull FuelError fuelError) { /* handle error */ }
});
if(isset($action) && $action='pay' && isset($amount)){
\Stripe\Stripe::setApiKey('sk_test_qrdTKAz2kaeZEPZHK2OdrNpn');
// Use an existing Customer ID if this is a returning customer.
$userid = $_GET['u'];
$query_usr = "SELECT * FROM tbl_user WHERE user_id = '$userid'";
$r_usr = $conn->query($query_usr);
$user = $r_usr->fetch_assoc();
if($user['stripe_customer'] == NULL){
$customer = \Stripe\Customer::create([
'name' => $user['user_name'],
'email' => $user['user_email']
]);
$customer_id = $customer->id;
$conn->query("UPDATE tbl_user SET stripe_customer = '$customer_id' WHERE user_id = $userid");
}
else{
$customer_id = $user['stripe_customer'];
}
$ephemeralKey = \Stripe\EphemeralKey::create(
[
'customer' => $customer_id,
],
[
'stripe_version' => '2020-08-27',
]);
$paymentIntent = \Stripe\PaymentIntent::create([
'amount' => 1099,
'currency' => 'cad',
'customer' => $customer_id,
'automatic_payment_methods' => [
'enabled' => 'true',
],
]);
$si = \Stripe\SetupIntent::create([
'customer' => $customer_id
]);
$response['paymentIntent'] = $paymentIntent->client_secret;
$response['setupIntent'] = $si->client_secret;
$response['ephemeralKey']= $ephemeralKey->secret;
$response['customer']= $customer_id;
$response['publishableKey'] = 'pk_test_0aSL6prHXE16hsokTWYKk8Gz';
echo json_encode($response);
// return $response->withJson([
// 'paymentIntent' => $paymentIntent->client_secret,
// 'ephemeralKey' => $ephemeralKey->secret,
// 'customer' => $customer_id,
// 'publishableKey' => 'pk_live_8mBL0Iji2oVDpgmBAVwPiicC'
// ])->withStatus(200);
}
else
{
$response['error']=TRUE;
$response['error_msg']="Required Parameters are missing";
echo json_encode($response);
}
private void presentPaymentSheet() {
final PaymentSheet.Configuration configuration = new PaymentSheet.Configuration.Builder("!2min, Inc.")
.customer(customerConfig)
// Set `allowsDelayedPaymentMethods` to true if your business can handle payment methods
// that complete payment after a delay, like SEPA Debit and Sofort.
.allowsDelayedPaymentMethods(true).build();
paymentSheet.presentWithSetupIntent(
paymentIntentClientSecret,
configuration
);
}
private void onPaymentSheetResult(final PaymentSheetResult paymentSheetResult) {
if (paymentSheetResult instanceof PaymentSheetResult.Canceled) {
Log.d("cantag","Canceled");
} else if (paymentSheetResult instanceof PaymentSheetResult.Failed) {
Log.e("App", "Got error: ", ((PaymentSheetResult.Failed) paymentSheetResult).getError());
} else if (paymentSheetResult instanceof PaymentSheetResult.Completed) {
// Display for example, an order confirmation screen
Log.d("tcmp","Completed");
}
}
Based off the error message, you should be passing in a SetupIntent's client_secret - a SetupIntent id starts with si_ . However, you're passing in a PaymentIntent's client_secret - a PaymentIntent id starts with pi_
If you intend to use a PaymentIntent, you should follow the guide here : https://stripe.com/docs/payments/accept-a-payment?platform=android
If you intend to use a SetupIntent, you should follow the guide here : https://stripe.com/docs/payments/save-and-reuse?platform=android&ui=payment-sheet
I'm trying to deploy a smart contract, but before doing so I'm accessing${basePath}/build/ipfsMetasGeneric/_ipfsMetasResponse.json and picking up the metaData.metadata_uri to assign it to PREREVEAL_TOKEN_URI. It all works well until there (I can see on the terminal the console.log (PREREVEAL_TOKEN_URI)). But the app stop working right after as it catches an error and throws me the message CATCH ERROR: ERROR STATUS: 403.
I'm just quite puzzled since I don't understand why the try code runs all Ok but then throws me that error. I've hit a roadblock, would appreciate any help.
Thank you.
Code follows:
const path = require("path");
const basePath = process.cwd();
const fs = require("fs");
const yesno = require('yesno');
const {
fetchNoRetry,
} = require(`${basePath}/utils/functions/fetchWithRetry.js`);
let {
CHAIN,
GENERIC,
CONTRACT_NAME,
CONTRACT_SYMBOL,
METADATA_UPDATABLE,
ROYALTY_SHARE,
ROYALTY_ADDRESS,
MAX_SUPPLY,
MINT_PRICE,
TOKENS_PER_MINT,
OWNER_ADDRESS,
TREASURY_ADDRESS,
PUBLIC_MINT_START_DATE,
BASE_URI,
PREREVEAL_TOKEN_URI,
PRESALE_MINT_START_DATE,
PRESALE_WHITELISTED_ADDRESSES
} = require(`${basePath}/src/config.js`);
const deployContract = async () => {
const ok = await yesno({
question: `Is all REQUIRED contract information correct in config.js? (y/n):`,
default: null,
});
if(!ok) {
console.log("Exiting...");
process.exit(0);
}
if(GENERIC) {
try {
let jsonFile = fs.readFileSync(`${basePath}/build/ipfsMetasGeneric/_ipfsMetasResponse.json`);
let metaData = JSON.parse(jsonFile);
console.log (metaData);
if(metaData.response === "OK") {
if(!PREREVEAL_TOKEN_URI) {
PREREVEAL_TOKEN_URI = metaData.metadata_uri;
console.log (PREREVEAL_TOKEN_URI);
}
} else {
console.log('There is an issue with the metadata upload. Please check the /build/_ipfsMetasGeneric/_ipfsMetasResponse.json file for more information. Running "npm run upload_metadata" may fix this issue.');
}
} catch (err) {
console.log(`/build/_ipfsMetasGeneric/_ipfsMetasResponse.json file not found. Run "npm run upload_metadata" first.`);
console.log(`Catch: ${err}`);
process.exit(0);
}
} else {
try {
let jsonFile = fs.readFileSync(`${basePath}/build/ipfsMetas/_ipfsMetasResponse.json`);
let metaData = JSON.parse(jsonFile);
if(metaData.response === "OK") {
if(!BASE_URI) {
BASE_URI = metaData.metadata_directory_ipfs_uri;
}
} else {
console.log('There is an issue with the metadata upload. Please check the /build/_ipfsMetas/_ipfsMetasResponse.json file for more information. Running "npm run upload_metadata" may fix this issue.');
}
} catch (err) {
console.log(`/build/_ipfsMetasGeneric/_ipfsMetasResponse.json file not found. Run "npm run upload_metadata" first.`);
process.exit(0);
}
}
if (!fs.existsSync(path.join(`${basePath}/build`, "/contract"))) {
fs.mkdirSync(path.join(`${basePath}/build`, "contract"));
}
try {
const url = `https://api.nftport.xyz/v0/contracts/collections`;
const contract = {
chain: CHAIN.toLowerCase(),
name: CONTRACT_NAME,
symbol: CONTRACT_SYMBOL,
owner_address: OWNER_ADDRESS,
metadata_updatable: METADATA_UPDATABLE,
royalties_share: ROYALTY_SHARE,
royalties_address: ROYALTY_ADDRESS,
max_supply: MAX_SUPPLY,
mint_price: MINT_PRICE,
tokens_per_mint: TOKENS_PER_MINT,
treasury_address: TREASURY_ADDRESS,
public_mint_start_date: PUBLIC_MINT_START_DATE,
presale_mint_start_date: PRESALE_MINT_START_DATE,
base_uri: BASE_URI,
prereveal_token_uri: PREREVEAL_TOKEN_URI,
presale_whitelisted_addresses: PRESALE_WHITELISTED_ADDRESSES
};
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(contract),
};
const response = await fetchNoRetry(url, options);
fs.writeFileSync(`${basePath}/build/contract/_deployContractResponse.json`, JSON.stringify(response, null, 2));
if(response.response === "OK") {
console.log(`Contract deployment started.`);
} else {
console.log(`Contract deployment failed`);
}
console.log(`Check /build/contract/_deployContractResponse.json for more information. Run "npm run get_contract" to get the contract details.`);
} catch (error) {
console.log(`CATCH: Contract deployment failed`, `ERROR: ${error}`);
}
};
deployContract();
I have a firebase cloud function written in node.js which is called from a custom swift class but when I try to execute the cloud function I don't get the link token back, just nil.
Here is my cloud function:
// PLAID
const plaid = require('plaid');
exports.createPlaidLinkToken = functions.https.onCall(async (data, context) => {
const customerId = context.auth.uid
const plaidClient = new plaid.Client({
clientID: functions.config().plaid.client_id,
secret: functions.config().plaid.secret,
env: plaid.environments.sandbox,
options: {
version: '2019-05-29'
}
})
return plaidClient.createLinkToken({
user: {
client_user_id: customerId
},
client_name: 'Bon Voyage',
products: ['auth'],
country_codes: ['US'],
language: 'en'
})
.then((apiResponse) => {
const linkToken = apiResponse.link_token
return linkToken
})
.catch((err) => {
functions.logger.log(err)
throw new functions.https.HttpsError('internal', 'Unable to create plaid link token: ' + err)
})
})
and here is my custom swift class:
class PlaidApi {
class func createLinkToken(completion: #escaping (String?) -> () ) {
Functions.functions().httpsCallable("createPlaidLinkToken").call { (result, error) in
if let error = error {
debugPrint("Got here 1: \(error.localizedDescription)")
return completion(nil)
}
guard let linkToken = result?.data as? String else { print("Got here 2"); return completion(nil) }
completion(linkToken)
}
}
}
here is where is call the class function:
#IBAction func userIconClicked(_ sender: Any) {
let userActionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let logOut = UIAlertAction(title: "Log Out", style: .default) { (action) in
// Logout
do {
try Auth.auth().signOut()
print("DEBUG: got here")
} catch {
print("DEBUG: \(error.localizedDescription)")
}
}
let manageCreditCards = UIAlertAction(title: "Manage Credit Cards", style: .default) { (action) in
// Display Stripe Widget
self.paymentContext.pushPaymentOptionsViewController()
}
let manageBankAccounts = UIAlertAction(title: "Manage Bank Accounts", style: .default) { (action) in
// Display Bank Accounts
PlaidApi.createLinkToken { linkToken in
print(linkToken)
}
}
let closeAlertAction = UIAlertAction(title: "Close", style: .cancel)
userActionSheet.addAction(logOut)
userActionSheet.addAction(manageCreditCards)
userActionSheet.addAction(manageBankAccounts)
userActionSheet.addAction(closeAlertAction)
present(userActionSheet, animated: true)
}
As I said I only get the error message "Got here 1: The data couldn't be read because it isn't in the correct format." nil printed out in the Xcode debugger window.
Got it working! I was using the wrong Xcode environment in my project. I have a production environment and a development environment. I was using the production environment instead of the development environment. So my swift code was trying to invoke a cloud function in the production firebase cloud functions which only existed in the development firebase cloud functions.
problem
How to get response body on invoke next context using custom middle ware ??
After reach to line of await _next.Invoke(context) from debug;
not return json data from action result getusermenu
[HttpGet(Contracts.ApiRoutes.Security.GetUserMenus)]
public IActionResult GetUserMenu(string userId)
{
string strUserMenus = _SecurityService.GetUserMenus(userId);
return Ok(strUserMenus);
}
I need to get response body from action result above
header :
key : Authorization
value : ehhhheeedff .
my code i try it :
public async Task InvokeAsync(HttpContext context, DataContext dataContext)
{
// than you logic to validate token
if (!validKey)
{
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
await context.Response.WriteAsync("Invalid Token");
}
//if valid than next middleware Invoke
else
{
await _next.Invoke(context);
// i need after that get result on last of thread meaning return data of usermenu
}
}
}
public static class TokenExtensions
{
public static IApplicationBuilder UseTokenAuth(this IApplicationBuilder builder)
{
return builder.UseMiddleware<TokenValidateMiddleware>();
}
}
[no return data from access token][1]
https://i.stack.imgur.com/PHUMs.png
if(validtoken)
{
continue display getusermenuaction and show result
}
when valid token it return data like below on browser googlechrom
[
{
"form_name": "FrmAddPrograms",
"title": "Adding Screens",
"url": "",
"permissions": {
"Insert": "True",
"Edit": "True",
"Read": "True",
"Delete": "True",
"Print": "True",
"Excel": "False",
"RecordList": "False"
}
},
but on my app browser return
not valid token
Try to get response body in custom middleware using below code:
public class CustomMiddleware
{
private readonly RequestDelegate next;
public CustomMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
if (!validKey)
{
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
await context.Response.WriteAsync("Invalid Token");
}
//if valid than next middleware Invoke
else
{
Stream originalBody = context.Response.Body;
try
{
using (var memStream = new MemoryStream())
{
context.Response.Body = memStream;
await next(context);
memStream.Position = 0;
string responseBody = new StreamReader(memStream).ReadToEnd();//get response body here after next.Invoke()
memStream.Position = 0;
await memStream.CopyToAsync(originalBody);
}
}
finally
{
context.Response.Body = originalBody;
}
}
}
}
I'm trying to create an application with NestJS framework and I'd like to check if a specific Service is in the application context but, the framework default behavior is exiting the process when it doesn't find the Service inside the context.
I've surrounded the get method with try...catch but it doesn't work because of the process.exit(1) execution.
private async loadConfigService(server: INestApplication): Promise<void> {
try {
this.configService = await server.get<ConfigService>(ConfigService, { strict: false });
} catch (error) {
this.logger.debug('Server does not have a config module loaded. Loading defaults...');
}
this.port = this.configService ? this.configService.port : DEFAULT_PORT;
this.environment = this.configService ? this.configService.environment : Environment[process.env.NODE_ENV] || Environment.DEVELOPMENT;
this.isProduction = this.configService ? this.configService.isProduction : false;
}
I'd like to catch the exception to manage the result instead of exiting the process.
Here's what I came up with:
import { NestFactory } from '#nestjs/core';
export class CustomNestFactory {
constructor() {}
public static create(module, serverOrOptions, options) {
const ob = NestFactory as any;
ob.__proto__.createExceptionZone = (receiver, prop) => {
return (...args) => {
const result = receiver[prop](...args);
return result;
};
};
return NestFactory.create(module, serverOrOptions, options);
}
}
Now, instead of using the default NestFactory I can use my CustomNestFactory
Dirty, but it works
Here is my code to solve same issue:
import { ExceptiinsZone } from '#nestjs/core/errors/exceptions-zone';
ExceptionsZone.run = callback => {
try {
callback();
} catch (e) {
ExceptionsZone.exceptionHandler.handle(e);
throw e;
}
};
You may need to override asyncRun() also for other method.