Asp.net resources - prevent error on page when resource reference is invalid
I'm using resources like this; " runat="server" />
Resources are maintained in a database and resourcefiles are generated when new translations are added. Sometimes bad references to keys happens. This results in error on the whole page.
How can I prevent the whole page fro开发者_运维技巧m crashing when a resource does not exist? I just want a tiny error message where the resource lacks, like "Not found: Users.DetailsUserHeadline".
I also want to dynamically retrieve resources from code behind, by defining the key as a string "Users.DetailsUserHeadline" without any erros.
Suggestions?
If you want to use the ResourceKey instead if the resource is not found, just modify the method which is used to get the resource. It should look like:
public class ResourceManager
{
public static string GetResource(string key)
{
string val = TryGet(key);
if (string.IsNullorEmpty(val)) val = key;
return val;
//or you don't use a TryGet method
//try
//{
// val = GetTheResource(key);
//}
//catch (ResourceNotFoundException e)
//{
// val = key;
//}
}
}
If you want to show a prompt that the resource is not found to users, you need to write your own exception like:
public class ResourceNotFoundException : Exception
{
// define the properties you want to get
}
And use throw new ResourceNotFoundException()
when you try to get the resource. In your UI part you can catch the exception and show something to users.
精彩评论