Sharp image uploader not working when running app with PM2 - express

I have an express app that I am using Sharp to resize images after a user has uploaded them. When I start the app using 'npm start' I am able to upload the images with no issues, but if I use PM2 to manage the process the images don't get saved on the server. I can save them without using Sharp to resize them, it is only when I have the code for sharp that they don't get saved. Below is the code from my controller. Multer is processing the form and sharp is resizing the image.
doNewRecipe: function(req, res) {
for (var key in req.body) {
req.body[key] = req.body[key] || undefined;
}
var body = _.pick(req.body, 'title', 'description', 'ingredients', 'instructions', 'yield', 'prep_time', 'cook_time', 'categoryId');
body.userId = req.session.user.id;
if (req.file) {
var tempPath = req.file.path,
ext = path.extname(req.file.originalname).toLowerCase(),
//targetPath = path.resolve(finalUploadPath + req.file.filename + ext);
targetPath = path.resolve(finalUploadPath);
fs.renameSync(tempPath, tempPath + ext);
var newFileName = req.file.filename + ext;
var imageFile = tempPath + ext;
body.image = newFileName;
sharp(imageFile)
.resize(450, 450)
.max()
.toFile('./public/finalUpload/' + newFileName, function(err, info) {
body.image = newFileName;
fs.unlinkSync(path.resolve(tempPath + ext));
db.recipe.create(body).then(function(recipe) {
res.redirect('/recipe/view/' + recipe.id);
}, function(e) {
console.log(e.message);
res.render('error', {message: e.toString()});
});
});
//fs.renameSync(tempPath, targetPath);
} else {
db.recipe.create(body).then(function(recipe) {
res.redirect('/recipe/view/' + recipe.id);
}, function(e) {
console.log(e.message);
res.render('error', {message: e.toString()});
});
}
},

If you use path to determine where to save the file it will transport easily from one system to another. I actually created a few variables to determine where to save the file. Below is my code.
if (process.env.NODE_ENV === 'production') {
var finalUploadPath = 'hidden';
var googleTracking = true;
} else if (process.env.NODE_ENV === 'staging') {
var finalUploadPath = 'hidden';
var googleTracking = false;
} else {
var finalUploadPath = 'hidden';
var googleTracking = false;
}
sharp(imageFile)
.resize(450, 450)
.max()
.toFile(finalUploadPath + req.file.filename + '.jpg', function(err, info) {
body.image = req.file.filename + '.jpg';
fs.unlinkSync(path.resolve(tempPath + ext));
compressAndResize(path.resolve(__dirname, '../public/finalUpload/' + body.image));
db.recipe.create(body).then(function(recipe) {
req.flash('success', 'Recipe created');
res.redirect('/recipe/view/' + recipe.id + '/' + recipe.slug);
}, function(e) {
console.log(e.message);
req.flash('error', 'Error creating new recipe');
res.render('error', {message: e.toString(), csrfToken: req.csrfToken(), google: googleTracking});
});
});

Related

angular 8- webrtc-adapter in Firefox not working

I try to run poc which created in angular 8 using webrtc-adpater. Problem is that it is not working in firefox and safari, but working in chrome.
What I observe connection is never connecting or connected in firefox.
I import webrtc in code so anything else we need to handle for firefox and safari.
Basically from Wowza I trying to consume streaming.
Below code sample which working in chrome but not in Firefox and safari:
const ICE_SERVERS: RTCIceServer[] = [
{ urls: ['stun:stun.example.com', 'stun:stun-1.example.com'] },
{ urls: 'stun:stun.l.google.com:19302' }
];
setupSignalingServer(ele) {
const self = this;
window.RTCPeerConnection = window.RTCPeerConnection ||
window.mozRTCPeerConnection ||
window.webkitRTCPeerConnection;
let signalingConnection = new WebSocket('wss://local.geofabricdev.com/webrtc-session.json');
signalingConnection.binaryType = 'arraybuffer';
signalingConnection.onopen = function (res) {
console.log('connection open');
signalingConnection.onerror = self.errorHandler;
// window.RTCPeerConnection = self.getRTCPeerConnection();
const peerConnection = new RTCPeerConnection(PEER_CONNECTION_CONFIG);
peerConnection.addEventListener('connectionstatechange', event => {
console.log(event);
if (peerConnection.connectionState === 'connected') {
console.log('connected');
}
});
peerConnection.addEventListener('icecandidate', event => {
console.log('peerconnection state5:' + peerConnection.connectionState);
if (event.candidate) {
// signalingChannel.send({'new-ice-candidate': event.candidate});
}
});
peerConnection.addEventListener('track', async event => {
console.log('gotRemoteTrack: kind:' + event.track.kind + ' stream:' + event.streams[0]);
const video = self.createVideo();
// const remoteVideo1 = document.querySelector('#remoteVideo') as HTMLVideoElement;
try {
video.srcObject = event.streams[0];
// remoteVideo1.srcObject = event.streams[0];
} catch (error) {
video.src = window.URL.createObjectURL(event.streams[0]);
}
});
signalingConnection.addEventListener('message', async message => {
console.dir(message);
// self.getSignalMessageCallback(message);
console.log('wsConnection.onmessage: ' + message.data);
const signal = JSON.parse(message.data);
if(signal.status !== 200) {
const video = self.createVideo();
video.poster = '../assets/streaming-error.png';
}
const streamInfoResponse = signal['streamInfo'];
let g = [];
// self.socketStream.some((f) => {
g = self.streams.filter((str) => signal['streamInfo'].streamName === str.streamName);
// if(g.length > 0) {
// return true;
// }
// });
// });
if (streamInfoResponse !== undefined) {
g[0]['sessionId'] = streamInfoResponse.sessionId;
}
console.log('Received signal');
const msgCommand = signal['command'];
console.log(msgCommand);
if (signal.sdp) {
peerConnection.setRemoteDescription(new RTCSessionDescription(signal.sdp));
if (signal.sdp) {
const description = await peerConnection.createAnswer();
await peerConnection.setLocalDescription(description);
signalingConnection.send('{"direction":"play", "command":"sendResponse", "streamInfo":' +
JSON.stringify(g[0]) + ', "sdp":' + JSON.stringify(description) + ',"userData":' + JSON.stringify(self.userData) + '}');
}
// })
// .catch(self.errorHandler);
} else if (signal.iceCandidates) {
console.log('ice: ' + JSON.stringify(signal.iceCandidates));
peerConnection.addIceCandidate(new RTCIceCandidate(signal.iceCandidates[0])).catch(self.errorHandler);
}
if ('sendResponse'.localeCompare(msgCommand) === 0) {
if (signalingConnection != null) {
signalingConnection.close();
}
signalingConnection = null;
}
// };
});
signalingConnection.send('{"direction":"play", "command":"getOffer", "streamInfo":' +
JSON.stringify(ele) + ', "userData":' + JSON.stringify(self.userData) + '}');
};
signalingConnection.onclose = function (r) {
console.log('close');
};
}
private createVideo() {
const video = document.createElement('video');
video.classList.add('cameraPanel');
video.autoplay = true;
video.preload = 'true';
video.muted = true;
video.width = 300;
const remoteVideo = document.querySelector('#videoContainer') as HTMLElement;
remoteVideo.appendChild(video);
return video;
}

multer-s3 rename files uploads same image multiple times

Help! No mater what I do I cant seem to give an image a custom file name using multer-s3. I have this really cool custom function that uploads images to s3. It works fine if I use the files original file name however when I try to use a custom file name it will upload the first image three times under the new file names. If anyone has any suggestions, insights or knows why this doesnt work. I'd apprecaite it.
var AWS = require("../AWS").AWS;
var s3 = require("../AWS").s3;
var multer = require("multer");
var multerS3 = require("multer-s3");
function generateKey(file, newFileName) {
// var finalFileName = newFileName + "." + file.originalname.split(".")[1];
var finalFileName = newFileName + "." + file.originalname.split(".")[1];
return finalFileName;
}
async function singleFileUpload(req, res, newFileName, bucketName, fieldName) {
var fileFilter = (req, file, cb) => {
var ext = file.originalname.split(".").slice(-1);
if (ext == "jpg" || ext == "mp4" || ext == "wmv") {
cb(null, true);
} else {
cb(new Error("invalid file format"), false);
}
};
var upload = multer({
fileFilter,
storage: multerS3({
s3,
bucket: bucketName,
acl: "public-read",
metadata: function(req, file, cb) {
cb(null, { test: "testing_meta_data!" });
},
// key: function(req, file, cb) {
// // let fileExtension = file.originalname.split(".")[1];
// let finalFileName = file.originalname;
// console.log(finalFileName);
// cb(null, finalFileName);
// }
key: function(req, file, cb) {
var newKey = generateKey(file, newFileName);
console.log("newKey", newKey);
cb(null, newKey);
}
})
});
console.log(fieldName);
var singleUpload = upload.any(fieldName);
await singleUpload(req, res, error => {
if (error) {
throw error;
} else {
console.log("it worked");
}
});
}
Than i call my custom function like so
singleFileUpload(req, res, "myNewFileName" "mybucketName", fieldName);
I call this several times because I want the ability to rename each file.
Thanks.
this code works.
var upload = multer({
storage: multerS3({
s3,
bucket: process.env.BUCKET_NAME,
metadata: function(req, file, cb) {
cb(null, { fieldName: file.fieldname });
},
key: function(req, file, cb) {
cb(null, reNameFiles(file, req.body.id, req.originalUrl));
},
contentType: multerS3.AUTO_CONTENT_TYPE
})
});
function reNameFiles(file, id, type) {
let lastIndex = type.lastIndexOf("/");
let videoType = type.slice(lastIndex + 1);
let finalFileName = "";
if (videoType == "templateMainVideoThumbnail") {
finalFileName =
"templates/" +
id +
"/main/original/" +
"video" +
"." +
file.originalname.split(".").slice(-1);
return finalFileName;
}
for (let i = 1; i <= 4; i++) {
if (videoType === "templateExampleVideo" + i) {
finalFileName =
"templates/" +
id +
"/example" +
i.toString() +
"/original/example" +
i.toString() +
"." +
file.originalname.split(".").slice(-1);
return finalFileName;
}
}
for (let j = 1; j <= 4; j++) {
if (videoType === "templateExamplePoster" + j) {
finalFileName =
"templates/" +
id +
"/example" +
j.toString() +
"/poster." +
file.originalname.split(".").slice(-1);
return finalFileName;
}
}
if (videoType === "templatePosterImage") {
finalFileName =
"templates/" +
id +
"/poster/poster" +
"." +
file.originalname.split(".").slice(-1);
return finalFileName;
}
if (videoType == "templateThumbnailFiles") {
let cleanOrginalName = file.originalname.replace(/\s/g, "");
finalFileName =
"templates/" + id + "/thumbnails/" + Date.now() + cleanOrginalName;
return finalFileName;
}
if (videoType == "stockMainVideoThumbnail") {
finalFileName =
"stock/" +
id +
"/main/original/" +
"video" +
"." +
file.originalname.split(".").slice(-1);
return finalFileName;
}
if (videoType == "stockPosterImage") {
finalFileName =
"stock/" +
id +
"/poster/poster" +
"." +
file.originalname.split(".").slice(-1);
return finalFileName;
}
if (videoType == "stockDownloadableFiles") {
finalFileName = "stock/" + id + "/downloadable/" + file.originalname;
return finalFileName;
}
}
I am using this approach for renaming and uploading my file through s3-multer you can use the same:
key: function (req, file, cb) {
file.originalname = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)+path.extname(file.originalname);
var fullPath = 'public/signature/'+ file.originalname;
cb(null, fullPath)
}

Loading webpage incompletely Phantomjs

I have problems capturing and loading the webpage:
https://myaccount.nytimes.com/auth/login
The username and password fields as well as the submit button are missing. What could be the reason? Thanks
As you can see the code listed below waits for each and all the resources to be loaded, one by one.
I did not write the code, however it is excellent and tested by many. The original can be found here:
https://gist.github.com/cjoudrey/1341747
(ALL the credits to the guy who wrote it.)
var resourceWait = 3000,
maxRenderWait = 30000,
url = 'https://myaccount.nytimes.com/auth/login'; //'https://twitter.com/#!/nodejs';
var page = require('webpage').create(),
count = 0,
forcedRenderTimeout,
renderTimeout;
page.viewportSize = { width: 1280, height : 1024 };
function doRender() {
page.render('twitter.png');
phantom.exit();
}
page.onResourceRequested = function (req) {
count += 1;
console.log('> ' + req.id + ' - ' + req.url);
clearTimeout(renderTimeout);
};
page.onResourceReceived = function (res) {
if (!res.stage || res.stage === 'end') {
count -= 1;
console.log(res.id + ' ' + res.status + ' - ' + res.url);
if (count === 0) {
renderTimeout = setTimeout(doRender, resourceWait);
}
}
};
page.open(url, function (status) {
if (status !== "success") {
console.log('Unable to load url');
phantom.exit();
} else {
forcedRenderTimeout = setTimeout(function () {
console.log(count);
doRender();
}, maxRenderWait);
}
});

Express Deprecated

I have a photo app that uploads photos to AWS. When testing the uploading photos feature on my localhost, my terminal throws the following error:
express deprecated res.send(status, body): Use
res.status(status).send(body) instead aws/aws.js:50:18
My photos DO save to AWS, im just wondering what this error is and how to fix it. Below is my aws code that the error refers too.
'use strict';
var AWS = require('aws-sdk'),
crypto = require('crypto'),
config = require('./aws.json'),
createS3Policy,
getExpiryTime;
getExpiryTime = function () {
var _date = new Date();
return '' + (_date.getFullYear()) + '-' + (_date.getMonth() + 1) + '-' +
(_date.getDate() + 1) + 'T' + (_date.getHours() + 3) + ':' + '00:00.000Z';
};
createS3Policy = function(contentType, callback) {
var date = new Date();
var s3Policy = {
'expiration': getExpiryTime(),
'conditions': [
['starts-with', '$key', 'images/'],
{'bucket': config.bucket},
{'acl': 'public-read'},
['starts-with', '$Content-Type', contentType],
{'success_action_status' : '201'}
]
};
// stringify and encode the policy
var stringPolicy = JSON.stringify(s3Policy);
var base64Policy = new Buffer(stringPolicy, 'utf-8').toString('base64');
// sign the base64 encoded policy
var signature = crypto.createHmac('sha1', config.secretAccessKey)
.update(new Buffer(base64Policy, 'utf-8')).digest('base64');
// build the results object
var s3Credentials = {
s3Policy: base64Policy,
s3Signature: signature,
AWSAccessKeyId: config.accessKeyId
};
// send it back
callback(s3Credentials);
};
exports.getS3Policy = function(req, res) {
createS3Policy(req.query.mimeType, function (creds, err) {
if (!err) {
return res.send(200, creds);
} else {
return res.send(500, err);
}
});
};
Replace res.send(statusCode, "something") with res.status(statusCode).send("something")
This should do it for your code:
exports.getS3Policy = function(req, res) {
createS3Policy(req.query.mimeType, function (creds, err) {
if (!err) {
return res.send(creds); //200 is not needed here, express will default to this
} else {
return res.status(500).send(err);
}
});
};

Large file upload and download ASP .NET MVC4

Can anybody give me example of code for uploading and downloading different type of files by Using Custom Control in ASP .NET MVC4 by using PlUpload Plugin. I want to save files for my task, message with unique Ids in database and want to retrieve them too. Here is my code that I tried for uploading
server side
public ActionResult UploadFiles(string id)
{
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
file.SaveAs(AppDomain.CurrentDomain.BaseDirectory + "Uploads/" + file.FileName);
}
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
and for plupload plugin code for client side for uploading file is
$("#file_attachments").pluploadQueue(
{
// General settings
runtimes: 'html5,flash,silverlight',
url: '/SideMenuBar/UploadFiles',
max_file_size: '100mb',
chunk_size: '1mb',
unique_names: true,
multipart: true,
// Specify what files to browse for
filters: [
{ title: "Image files", extensions: "jpg,gif,png" },
{ title: "Zip files", extensions: "zip" },
{ title: "Rar files", extensions: "rar" },
{ title: "Document files", extensions: "docx,doc,xlx,xlxs,ppt" },
],
// Flash settings
flash_swf_url: 'Script/lib/plupload/js/plupload.flash.swf',
// Silverlight settings
silverlight_xap_url: 'Script/lib/plupload/js/plupload.silverlight.xap',
// PreInit events, bound before any internal events
preinit: {
Init: function (up, info) {
//alert('[Init]'+ info+ 'Features:'+ up.features);
},
UploadFile: function (up, file) {
// alert('[UploadFile]', file);
// You can override settings before the file is uploaded
up.settings.url = '/SideMenuBar/UploadFiles?id=' + file.id;
//up.settings.multipart_params = {param1: 'value1', param2: 'value2'};
}
},
// Post init events, bound after the internal events
init:
UploadComplete: function (up, files) {
// destroy the uploader and init a new one
up.destroy();
}
}
});
var uploader = $('#file_attachments').pluploadQueue();
uploader.bind('FileUploaded', function (upldr, file, object) {
if (uploader.files.length == (uploader.total.uploaded + uploader.total.failed)) {
$(".file_upload_cancel").hide();
$(".file_upload_done").show();
}
});
uploader.bind("FilesAdded", function (up, filesToBeAdded) {
if (up.files.length > 5) {
up.files.splice(4, up.files.length - 5);
showStatus("Only 5 files max are allowed per upload. Extra files removed.", 3000, true);
return false;
}
return true;
});
$('.upload_files').click(function (e) {
e.preventDefault();
$(".file_up").show();
});
$('#new_message_form').submit(function (e) {
var uploader = $('#file_attachments').pluploadQueue();
// Files in queue upload them first
if (uploader.files.length > 0) {
// When all files are uploaded submit form
uploader.bind('StateChanged', function () {
if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
//uncoment next line to submit form after all files are uploaded
//$('#new_message_form')[0].submit();
}
});
uploader.start();
}
return false;
});
}
How can I resolve problem
You are using an option called "chunk", which divides your file in the size of the chunk - it's a good practice, to prevent errors.
You have determined it with the property "chunk_size". For example: you have a file of 5mb. When you upload, you'll have 5 parts of 1mb - until the upload is complete. Then, you'll have to put them together.
I recommend you to see this link to more informations about chunk and how to make it work.
Here is an example of one of my implementation - with MVC 3 - of plupload with chunk.
I'll post the javascript code and the action. I think it will be good for you to know how to implement in your case.
function installFolderFileUploader(action, id, ProfileType, intMaxFilesPermitted, Folder, maxSizeMB) {
var uploaderRuntimes = 'html5, flash, silverlight';
var uploader = new plupload.Uploader({
runtimes: uploaderRuntimes,
browse_button: 'imgBtnPhotoUpload',
url: action,
flash_swf_url: '/Scripts/Plugins/Moxie.swf',
silverlight_xap_url: '/Scripts/Plugins/Moxie.xap',
multipart_params: { 'id': id, 'ProfileType': ProfileType },
multi_selection: true,
max_file_count: '5',
chunk_size: '100KB',
filters: {
max_file_size: maxSizeMB + 'MB'
},
init: {
FileUploaded: function (Up, File, Response) {
var jsonObj = jQuery.parseJSON(Response.response);
if (jsonObj.success) {
mountFileUploadFields(jsonObj, Folder, ProfileType);
}
},
PostInit: function () {
//meow
$('#imgBtnPhotoUpload').next().css({ 'top': '0', 'width': '146px', 'height': '28px', 'cursor': 'pointer' });
},
FilesAdded: function (up, files) {
var totalInPage = parseInt($('#dvFileContainer .BeeFileDetails').length);
if ((up.files.length + totalInPage) > parseInt(intMaxFilesPermitted)) {
jQuery.facebox({ div: "#dvMaxFilesPermitedError" });
up.splice();
up.refresh();
return false;
}
else {
if (totalInPage >= parseInt(intMaxFilesPermitted)) {
jQuery.facebox({ div: "#dvMaxFilesPermitedError" });
up.splice();
up.refresh();
return false;
}
else {
$('#dvFileList').css('margin-left', '2px');
$('#dvFileList').css('font-size', '10px');
$('#dvFileList').css('display', 'block');
plupload.each(files, function (file) {
$('#dvFileList').append('<div>');
$('#dvFileList').append('<div style="width:84%;margin-left:30px;float:left;" id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ')<b></b></div>');
$('#dvFileList').append('<img class="removeFile" style="margin-top:2px;cursor:pointer;" src="/Content/images/cancel.png" id="' + file.id + '" />');
$('#dvFileList').append('</div>');
$('.removeFile').on('click', function () {
$('#' + file.id).remove();
$('img[id=' + file.id + ']').remove();
uploader.stop();
uploader.splice();
});
});
uploader.start();
}
}
},
UploadProgress: function (up, file) {
if (file.percent == 100) {
$('#' + file.id).remove();
$('img[id=' + file.id + ']').remove();
}
$('#' + file.id + ' b:eq(0)').html('<span> - ' + file.percent + '%</span>');
$('#' + file.id + ' b:eq(0)').append('<div id="fileUploaded" style="background-color:#0099FF;height:3px;width:' + file.percent + '%";></div>');
},
ChunkUploaded: function (up, file, info) {
var jsonObj = jQuery.parseJSON(info.response);
if (jsonObj.tempFile != "") {
uploader.settings.multipart_params.tempFile = jsonObj.tempFile;
}
else {
$('#' + file.id).remove();
$('img[id=' + file.id + ']').remove();
var totalInPage = parseInt($('#dvFileContainer .BeeFileDetails').length);
if (totalInPage > 0)
$('.BeeEditFileActions').fadeIn();
var fileName = uploader.settings.multipart_params.tempFile;
removeNonUsedFiles(id, fileName, 'File');
uploader.settings.multipart_params.tempFile = '';
uploader.stop();
uploader.splice();
uploader.refresh();
jQuery.facebox({ div: "#dvAddFolderFileError" });
}
},
Error: function (up, err) {
if (err.code != '-500')
jQuery.facebox({ div: "#dvAddFolderFileError" });
},
UploadComplete: function (a, Response) {
$('.BeeEditFileActions').fadeIn();
$('#dvFileList').empty();
uploader.splice();
uploader.refresh();
}
}
});
uploader.init();
}
And the Action:
[AllowAnonymous]
[HttpPost]
public JsonResult UploadFolderFile(string id, Domain.Profile.TypeProfile ProfileType, string tempFile, string name, int? chunk, int? chunks)
{
String strTempFile = string.Empty;
String strSaveLocation = string.Empty;
try
{
var fileData = Request.Files[0];
chunk = chunk ?? 0;
String strExtension = Path.GetExtension(name).ToLower();
Models.Identity.CustomIdentity objUser = new Models.Identity.CustomIdentity(System.Web.Security.FormsAuthentication.Decrypt(id));
DB.CompanyNetworkDB objCompanyDB = new DB.CompanyNetworkDB();
Int32 intMaxFileSize = objCompanyDB.getFileInFolderMaxSize(objUser.CompanyNetworkID) * 1024 * 1024;
if (objUser != null && objUser.IsAuthenticated && fileData.ContentLength <= intMaxFileSize)
{
////Get upload file.
String strSaveLocationURL = Domain.Profile.getUploadItemsFolder(objUser.CompanyNetworkID, ProfileType, Domain.Profile.UploadType.Folder);
strSaveLocationURL += "temp/";
strSaveLocation = Server.MapPath(strSaveLocationURL);
strTempFile = string.IsNullOrEmpty(tempFile) ? DateTime.Now.Ticks.ToString() + strExtension : tempFile;
long fileSize = 0;
using (var fs = new FileStream(Path.Combine(strSaveLocation, strTempFile), chunk == 0 ? FileMode.Create : FileMode.Append))
{
var buffer = new byte[fileData.InputStream.Length];
fileData.InputStream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, buffer.Length);
fileSize = fs.Length;
}
if (fileSize <= intMaxFileSize)
{
if (chunk == chunks - 1)
{
return Json(new { success = true, OriginalFileName = Path.GetFileName(name), ServerFileName = strTempFile, SizeMB = fileSize });
}
else
{
return Json(new { success = true, tempFile = strTempFile });
}
}
else
{
return Json(new { success = false });
}
}
else
{
return Json(new { success = false });
}
}
catch (ArgumentOutOfRangeException)
{
System.IO.File.Delete(Path.Combine(strSaveLocation, strTempFile));
return Json(new { success = false, erro = "canceled" });
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
I think it could help.