I have read many articles now about how to handle errors in asp.net, and I think it is a lot of information to take in.
I'm using service layer pattern, and in my service model, I have the following code:
public List<SpotifyAlbumModel> AddSpotifyAlbums(List<SpotifyAlbumModel> albums)
{
try
{
if(albums != null)
{
ctx.SpotifyAlbums.AddRange(albums);
ctx.SaveChanges();
}
return albums;
}
catch(Exception e)
{
throw new Exception();
}
}
If a problem rises, I want to redirect the user to a error page that says something went wrong.
I call my service method from my controller:
public ActionResult AddSpotifyAlbums(List<SpotifyAlbumModel> albums)
{
_profileService.AddSpotifyAlbums(albums);
return Json(new { data = albums });
}
How can I determine in my controller method if something went wrong in the service, and then redirect the user to the error page?
Or should I have a global errorHandler that transfer the user as soon a excetion is caught?
You can add Application_Error method in global.asax. For example:
void Application_Error(Object sender, EventArgs e)
{
var exception = Server.GetLastError();
if (exception == null) {
return;
}
// Handle an exception here...
// Redirect to an error page
Response.Redirect("Error");
}
We've tried multiple things, but what seems to work best is to just handle every exception yourself. We didn't completely invent this yourself, the inspiration was from here:
ASP.NET MVC 404 Error Handling
protected void Application_EndRequest()
{
if (Context.Response.StatusCode == 404)
{
Log.Debug("Application_EndRequest:" + Context.Response.StatusCode + "; Url=" + Context.Request.Url);
Response.Clear();
string language = LanguageUtil.Instance.MapLanguageCodeToWebsiteUrlLanguage(HttpContext.Current.Request, Thread.CurrentThread.CurrentUICulture.Name);
var rd = new RouteData();
//rd.DataTokens["area"] = "AreaName"; // In case controller is in another area
rd.Values["languageCode"] = language;
rd.Values["controller"] = "Error404";
rd.Values["action"] = "Index";
Response.TrySkipIisCustomErrors = true;
IController c = new Controllers.Error404Controller();
c.Execute(new RequestContext(new HttpContextWrapper(Context), rd));
}
else if (Context.Response.StatusCode == 500)
{
Log.Debug("Application_EndRequest:" + Context.Response.StatusCode + "; Url=" + Context.Request.Url);
Response.Clear();
string language = LanguageUtil.Instance.MapLanguageCodeToWebsiteUrlLanguage(HttpContext.Current.Request, Thread.CurrentThread.CurrentUICulture.Name);
Response.Redirect("~/" + language + "/error");
}
}
Related
Is it possible that I would bind a method and fix the error in the catch response? (for example take this code below)
try
{
if (icheck == 0)
{
BindRegister();
}
else
{
Label1.Text = "Error Message";
}
}
catch
{
icheck = 0;
BindRegister();
}
Is the catch just responsible for writing down the error message? (I'm using this code in my ASP.net web app)
I used WebClient to download a file in my apk. But I got this error:
Unhandled Exception:
System.Net.WebException: An exception occurred during a WebClient request.
And this is the code that I tried:
{
using (WebClient client = new WebClient())
{
client.DownloadFile(
"https://code.org/images/social-media/code-2018-creativity.png",
#"j:\storage\emulated\legacy\Download\code-2018-creativity.png");
}
}
Since you are only referring to a WebException, it may have to do with one of these cases:
The URI formed by combining BaseAddress and address is invalid.
The file or destination folder does not exist. Make sure your path to
the destination folder already exists and that you have permissions to access it.
An error occurred while
downloading data.
If you provide us more information about the exception we may be able to reduce the error to one of these cases. To get the InnerException you can do something like this:
{
using (WebClient client = new WebClient ())
{
try
{
client.DownloadFile (
"https://code.org/images/social-media/code-2018-creativity.png",
#"j:\storage\emulated\legacy\Download\code-2018-creativity.png");
}
catch (Exception ex)
{
while (ex != null)
{
Console.WriteLine (ex.Message);
ex = ex.InnerException;
}
}
}
}
You have to ask permissions on run time even you have mentioned them in your manifest file if you are running Android api level 23 or greater.
Have a look at this blog would help about how to ask a run time permission:requesting-runtime-permissions-in-android
Also, this is the official sample of how to check RuntimePermissions
Refer: xamarin-system-unauthorizedaccessexception-access-to-the-path-is-denied
Update:
To ask run time permissions, you can use this plugin:Plugin.Permissions, install it to your project.
And then, call CheckMyPermissionAsync(); before you download the file:
private void FabOnClick(object sender, EventArgs eventArgs)
{
View view = (View) sender;
CheckMyPermissionAsync();
}
In the method CheckMyPermissionAsync(), check your Storage permission and then download file:
public async void CheckMyPermissionAsync()
{
var permissionsStartList = new List<Permission>()
{
Permission.Storage
};
var permissionsNeededList = new List<Permission>();
try
{
foreach (var permission in permissionsStartList)
{
var status = await CrossPermissions.Current.CheckPermissionStatusAsync(permission);
if (status != PermissionStatus.Granted)
{
permissionsNeededList.Add(permission);
}
}
}
catch (Exception ex)
{
}
var results = await CrossPermissions.Current.RequestPermissionsAsync(permissionsNeededList.ToArray());
//Check the persimmison again
var storeagePermission = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Storage);
if (storeagePermission == PermissionStatus.Granted)
{
//Download file here
DownloadFile("http://www.dada-data.net/uploads/image/hausmann_abcd.jpg", "XF_Downloads");
}
else {
Console.WriteLine("No permissions");
}
}
You can check the result in the completed event:
private void Completed(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
Console.WriteLine("success");
}
else
{
if (OnFileDownloaded != null) { }
Console.WriteLine("fail");
}
}
Note: pay attention to your filePath,make sure your path is correct, I use:
string pathToNewFolder = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, folder);
I updated my sample here: runtime-permission-xamarin.android
I've developed a simple Web Service and a Windows Phone 8 app to consume it.
Everything works as intended but the way my current (working) code stands, it's assuming the Web Service to always be running and available. Seeing as that may not always be the case, I'd like to try and add some kind of connectivity testing before I start sending requests. I've read that there's no straightforward way of being certain that the WS is up and running other than querying it somehow.
With that in mind, here's what my LoadData method structure looks like (Feb. 26th):
public void LoadData(string articleCode = null)
{
try
{
this.ArticleItems.Clear();
MyServiceSoapClient ws = new MyServiceSoapClient();
CheckWebService();
if (this.isWebServiceUp)
{
if (!String.IsNullOrEmpty(articleCode))
{
ws.GetBasicDataAsync(articleCode);
ws.GetBasicDataCompleted += Ws_GetBasicDataCompleted;
//(irrelevant code supressed for clarity)
this.IsDataLoaded = true;
}
}
else
{
this.ArticleItems.Add(new ItemViewModel() { LineOne = "Could not connect to Web Service." });
ws.Abort();
}
}
}
And it still throws an unhandled CommunicationException error.
EDIT: After taking into consideration both suggestions and doing some searching, I've tried to set up a "heartbeat"-type method but it's not working correctly. Asynchronous programming is a relatively new paradigm for me so I most likely am missing something but here goes my attempt at an implementation thus far (getting a "Unable to cast object of type 'System.Net.Browser.OHWRAsyncResult' to type 'System.Net.HttpWebResponse'" exception):
public void CheckWebService()
{
try
{
Uri wsURL = new Uri("http://localhost:60621/WebService1.asmx");
//try accessing the web service directly via its URL
var request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(wsURL);
request.Method = "HEAD";
//next line throws: "Unable to cast object of type 'System.Net.Browser.OHWRAsyncResult' to type 'System.Net.HttpWebResponse'."
using (var response = (System.Net.HttpWebResponse)request.BeginGetResponse(new AsyncCallback(ServiceCallback), request))
{
if (response.StatusCode != System.Net.HttpStatusCode.OK)
{
throw new Exception("Error locating web service");
}
}
}
catch (System.ServiceModel.FaultException fe)
{
this.ArticleItems.Add(new ItemViewModel() { LineOne = fe.Message });
}
catch (System.ServiceModel.CommunicationException ce)
{
this.ArticleItems.Add(new ItemViewModel() { LineOne = ce.Message });
}
catch (System.Net.WebException we)
{
this.ArticleItems.Add(new ItemViewModel() { LineOne = we.Message });
}
catch (Exception ex)
{
this.ArticleItems.Add(new ItemViewModel() { LineOne = ex.Message });
}
}
private void ServiceCallback(IAsyncResult asyncResult)
{
try
{
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)asyncResult.AsyncState;
using (var response = (System.Net.HttpWebResponse)request.EndGetResponse(asyncResult))
{
if (response != null && response.StatusCode == System.Net.HttpStatusCode.OK)
{
this.isWebServiceUp = true;
request.Abort();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
I'm currently having problem in my project. I'm having Code 4004 error in silverlight application. I don't know what I did wrong. Here are the image link.
http://s1100.photobucket.com/user/Fredi_Tansari/media/errorInsilverlight.png.html
here are the codes. After the the invalideoperation exception it goes to the unhandled exception error.
private void getstatusCompleted(LoadOperation<PatientStatus1> obj)
{
try
{
PatientStatus1 bc = obj.Entities.First();
if (bc != null)
{
MessageBox.Show("Patient has a status already, please use update instead new");
return;
}
else
{
MessageBox.Show("inserting new Patient status");
}
}
catch (InvalidOperationException e)
{
PatientStatus1 newPatientStatus = new PatientStatus1();
newPatientStatus.ColorCodeID = "1";
newPatientStatus.timestamp = DateTime.Now;
newPatientStatus.UserID = "Jimmi";
newPatientStatus.Patient_PatientID = Convert.ToInt32(patientIDTextBox.Text);
newPatientStatus.MasterPatientStatus_masterPatientStatusId = Convert.ToInt32(masterPatientStatusIdTextBox.Text);
newPatientStatus.MasterLocation_masterLocationID = Convert.ToInt32(masterLocationIDTextBox1.Text);
patientstatusDomainContext.PatientStatus1s.Add(newPatientStatus);
patientstatusDomainContext.SubmitChanges();
}
}
Thanks in advance for the help
Try to set this key value to 1.
HKEY_CURRENT_USER\Software\Microsoft\Windows Script\Settings\JITDebug
Good day to all! Trying to solve a problem. I use a method that handles all errors on the site (This method found on the blog of one man)
Global.asax
protected void Application_Error(object sender, EventArgs e)
{
HttpContext ctx = HttpContext.Current;
Exception ex = ctx.Server.GetLastError();
ctx.Response.Clear();
RequestContext rc = ((MvcHandler)ctx.CurrentHandler).RequestContext;
IController controller = new CategoryController();
var context = new ControllerContext(rc, (ControllerBase)controller);
var viewResult = new ViewResult();
var httpException = ex as HttpException;
if (httpException != null)
{
switch (httpException.GetHttpCode())
{
case 404:
viewResult.ViewName = "Error404";
break;
case 500:
viewResult.ViewName = "Error500";
break;
default:
viewResult.ViewName = "Error";
break;
}
}
else
{
viewResult.ViewName = "Error";
}
viewResult.ViewData.Model = new HandleErrorInfo(ex, context.RouteData.GetRequiredString("controller"), context.RouteData.GetRequiredString("action"));
viewResult.ExecuteResult(context);
ctx.Server.ClearError();
}
When I start Projects in the studio, causing the error. I get exception at that code:
RequestContext rc = ((MvcHandler)ctx.CurrentHandler).RequestContext;
Exception:
Unable to cast object of type 'System.Web.DefaultHttpHandler' to type 'System.Web.Mvc.MvcHandler'
Once I stop debugging (Shift + F5). This method works well and handles any errors. But at the start of project, causing the error. Looking for a solution to these topics, but this problem is not found. Help please.
[HandleError]
public class CategoryController : Controller
{
// some methods
}
Solved his problem by using code:
void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
if (ex is HttpException && ((HttpException)ex).GetHttpCode() == 404)
{
Response.Redirect("~/Error/404");
}
else
{
Response.Redirect("~/Error/Other");
}
Server.ClearError();
}