Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
Are there any best practices for documenting possible error codes returned from a Web API call? I'm referring to custom logic errors as opposed to standard HTTP return codes.
For example, consider an API method to allow a user to change their password. A possible error condition might be that the new password provided has already been used by that user previously (ie, password history requirement). You could use the following code to communicate that to the caller:
public HttpResponseMessage ChangePassword(string oldPassword, string newPassword)
{
try
{
passwordService.ChangePassword(oldPassword, newPassword)
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (Exception ex)
{
switch(ex.Message)
{
case "PasswordHistoryFailed":
return Request.CreateResponse(HttpStatusCode.BadRequest, new CustomErrorClass("FailedHistoryRequirements"));
break;
...
}
}
}
In this example, I'm using a custom error class to wrap a custom error code of "FailedHistoryRequirements". I could have more error codes for this operation such as too many password changes in a 24 hour period or whatever.
I want to know if there's an accepted way to automatically document these custom error codes in the method's XML Code Comments so that it can be consumed by a documentation generator like Swashbuckle/Swagger or something similar.
If you use Swagger, you can use the SwaggerResponse attribute.
Check out this blog post:
https://mattfrear.com/2015/04/21/generating-swagger-example-responses-with-swashbuckle/
I do this by catching a specific exception type, rather than parsing the message.
Here I have MyDepartmentCentricBaseException as a custom exception. I may have 2-3 exceptions that derive from it. But by using a base-exception, I keep my exception catching cleaner.
try
{
/* do something */
}
catch (MyDepartmentCentricBaseException deptEx)
{
HttpResponseException hrex = this.GetDepartmentMissingHttpResponseException(deptEx.DepartmentSurrogateKey);
throw hrex;
}
catch (Exception ex)
{
/* log it somewhere !*/
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
private HttpResponseException GetDepartmentMissingHttpResponseException(int DepartmentSurrogateKey)
{
HttpResponseMessage resp = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent(string.Format("No Department with DepartmentSurrogateKey = {0}", DepartmentSurrogateKey)),
ReasonPhrase = "DepartmentSurrogateKey Not Found"
};
HttpResponseException returnEx = new HttpResponseException(resp);
return returnEx;
}
There are other ideas here:
https://learn.microsoft.com/en-us/aspnet/web-api/overview/error-handling/exception-handling
But I don't know of a way of auto-voodoo-it with documentation. :(
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I wanted to understand how can I use Web sphere MQ for the following scenario:
1.How I can read the message from the queue without removing that message from the queue.
2. We have a web application so we need the Listener to read the Queue. Is there any tool to do this ?
Yes, it's possible to read message without removing from a queue, it's known as Browsing. You will need to create a browser consumer to read the messages. I have posted snippet here, same code is available in Tools\dotnet\samples\cs\xms\simple\wmq\SimpleQueueBrowser\SimpleQueueBrowser.cs also.
// Create connection.
IConnection connectionWMQ = cf.CreateConnection();
// Create session
ISession sessionWMQ = connectionWMQ.CreateSession(false, AcknowledgeMode.AutoAcknowledge);
// Create destination
IDestination destination = sessionWMQ.CreateQueue(queueName);
// Create consumer
IQueueBrowser queueBrowser = sessionWMQ.CreateBrowser(destination);
// Create message listener and assign it to consumer
MessageListener messageListener = new MessageListener(OnMessageCallback);
queueBrowser.MessageListener = messageListener;
// Start the connection to receive messages.
connectionWMQ.Start();
Callback method
static void OnMessageCallback(IMessage message)
{
try
{
// Display received message
Console.Write(message);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in OnMessageCallback: {0}", ex);
}
}
I am currently working in Enterprise Java and I'm a newbie. I am trying to create a method which should delete a selected item from a data table. My project contains Graphical User Interface elements from "http://www.primefaces.org/showcase/".
The deletion is made through a web-service.
This is the method I created so far:
public boolean delete(String articleId) {
Client client = ClientBuilder.newClient();
WebTarget target
= client.target(DELETE_URL);//this is a String
//TODO call ws method delete
try{
target.request()....;
} catch(Exception ex) {
LOGGER.error("Delete Article Error ", ex);
}
return true;
}
Could you tell me how can I handle the deletion in an appropiate way?
All the best!
In your case the following should do the trick.
target.request().delete(Response.class)
I have CORS working with the following:
[System.Web.Http.HttpPut]
[System.Web.Http.AcceptVerbs("OPTIONS")]
[System.Web.Http.Route("api/exercise")]
public HttpResponseMessage UpdateExercise(Exercise exercise) {
try {
_adminService.UpdateExercise(exercise);
return Request.CreateResponse(HttpStatusCode.OK, "Success");
} catch (Exception e) {
return Request.CreateResponse(HttpStatusCode.InternalServerError, e);
}
}
In my global.asax:
protected void Application_BeginRequest() {
if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS") {
Response.Flush();
}
}
But something weird is happening - if I set a breakpoint in my controller, the OPTIONS request makes its way to the innards with a null exercise. Why is this happening? I would expect the Flush() to prevent this.
As it stands, I need to add checks for null to all of my CORS-sensitive endpoints (PUTs, DELETEs). This seems inelegant... should I be able to prevent OPTIONS requests from hitting the controller logic, instead just responding with the required headers straight-away?
Adding this as an answer, based on the comments in the question.
The problem is caused by accepting the OPTIONS verb on the action method. The MVC runtime then tries to execute the action method & the null problem occurs.
Remove the verb so MVC doesn't try to execute the method & the Application_BeginRequest event will sort out the pre-flight issue for you.
This question already has answers here:
Getting warning from JSF: The response was already committed by the time we tried to set the outgoing cookie for the flash
(4 answers)
Closed 5 years ago.
I meet a strange behavior with JSF 2.4 on Mojarra.
I'm using flash parameters to pass from a page to another.
Each time i arrive on a new page, i retrieve my flash parameters in Postconstruct annoted method.
Then if the page is refreshed, the user is redirect to another page. (because the flash parameters are erased after refresh).
FOr the same code , i meet this error i if i populated my selectItems from different data (hard coded or database query) :
JSF1095: The response was already committed by the time we tried to set the outgoing cookie for the flash. Any values stored to the flash will not be available on the next request.
I d'like to get ride of this, maybe something to do with :
facesContext.responseComplete();
facesContext.renderResponse()
I don't understand how to use them.
I read about 2 :
<h:selectOneMenu id ="loc" value="#{participantController.localisation}"
validatorMessage="Vous devez renseigner la localisation." >
<f:selectItems value="#{participantController.locFeaturesList}"
var="locFeature" itemLabel="#{locFeature.locName}"
itemValue="#{locFeature.locName}" />
</h:selectOneMenu>
My list object :
public static class LocFeatures{
public String locName;
public String codeName;
public LocFeatures(String locName, String codeName){
this.locName = locName;
this.codeName = codeName;
}
public String getLocName(){
return locName;
}
public String getCodeName(){
return codeName;
}
}
Put data in my list object :
public LocFeatures[] loadLocalisationpAdicapCodeAssociativeMenu() {
List <Static> loc2Code = staticBo.get(STATIC_CATEGORY_PARTICIPANT_LOCALISATION_CODE);
locFeaturesList = new LocFeatures[loc2Code.size()+1];
// if I populate my list with only some values no errors will be thrown but it doesn't work when i populate it by a big database request
//locFeaturesList = new LocFeatures[1];
locFeaturesList[0] = new LocFeatures("-----",null); // Associations Classe - Name
int indice = 1;
for (Static assocation : loc2Code) {
locFeaturesList[indice] = new LocFeatures(assocation.getKey(),assocation.getValue()); // Associations Classe - Name
indice ++;
}
return locFeaturesList;
}
My #PostConstruct method :
#PostConstruct
public void setFlashParam() {
//locFeaturesList = loadLocalisationpAdicapCodeAssociativeMenu();
FacesContext facesContext = FacesContext.getCurrentInstance();
String studyNameFlashed = (String) facesContext.getExternalContext().getFlash().get("study_name");
// Gere un refresh qui ferait disparaitre le type de l'étude.
if (studyNameFlashed == null) {
try { ExternalContext ec = facesContext.getExternalContext(); ec.redirect(ec.getRequestContextPath() + "/Accueil"); } catch (IOException e) {e.printStackTrace();}
return;
}
return;
}
Try always to go with Mojarra latest versions to work with flash. In your case, try to update it to 2.2.6. As stated in several posts around here, there have been a lot of issues with flash scope in Mojarra implementations. However, it seems they've fixed the problem. See this answer (which BTW explains how to use the context properly).
See also:
JSF/Mojarra "flash scope" problems
Exception about flash in Mojarra JSF
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I am about to start writing a program that will have a GUI interface with the user that prompts for a number between 1-100. The program then emails me that number(this program would be running on an unknown users computer).
I am unable to decide what programing language to use for such a project. Can anyone suggest a language that is able to do GUI, and send emails from someone elses computer? (Preferable be able to save this program as a .exe or some single file that can be run from their computer. Also would prefer a link as to how to email in that language, but I am fine doing that research myself, just unsure what language to start researching in. If I left anything out please leave a comment asking for clarification. Thanks for any help I can get.
Use C# cus you know it's awesome (heavily biased answer) and here's the code
private bool sendMsg (string from, string to, string subject , string messageBody)
{
MailMessage message = null;
try
{
message = new MailMessage(from, to);
using (message) {
message.Subject = subject;
//message.CC.Add(CCemailAddress);
message.Body = messageBody;
message.IsBodyHtml = false;
SmtpClient client = new SmtpClient("smtp.outlook.com", 587);
client.Credentials = new System.Net.NetworkCredential(from, "Sending Accounts Password");
client.UseDefaultCredentials = false;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true; //enable SSL
client.Send(message);
client.Dispose();
}
}
catch
{
return false;
}
message.Dispose();
return true;
}