I'm trying to get more information for when google.script.run fails. I know that I can get a basic error handling callback function to give me the error message with something like this:
google.script.run.withFailureHandler(handleError).getMe();
Where handleError gets an argument passed in for the error message.
function handleError(error) {
console.log(error);
}
However, if I wanted to created a custom error handler that provided the location of where the exception was being thrown, I could use a custom function on withFailureHandler, like this:
google.script.run.withFailureHandler(function () {
showError(error, 'getMe');
}).getMe();
With this method I'm stumped with one issue. How do I capture the error message to pass to my showError() error handler?
Simply add the error parameter to your anonymous function.
google.script.run.withFailureHandler(function (error) {
showError(error, 'getMe');
}).getMe();
An errorHandler receives the error event from an exception that's thrown on the server. To pass a custom message, have your server side code do something like this:
...
if (errDetected) {
throw new error("Custom message")
}
...
Related
public UserMailDto getUserByEmail(String email) throws UserExceptionMessage {
try {
return userRepository.searchByMail(email);
} catch (DataAccessException | JDBCConnectionException accessException) {
com.example.user_service.config.log.Logger.errorLog("UserService", accessException.getMessage());
throw new DataAccessExceptionMessage(Messages.ERROR_TRY_AGAIN + accessException.getMessage());
}
}
In my view you should handle it, but not with a try..catch block in what seems to be your service. Why are you catching the Exception and then rethrowing you own custom Exception with a message? You will need to handle that Exception at some point in your code to. So you are not really handling it here.
It looks like you are building a web app, so I would recommend that you handle your Exceptions in one central place in a #ControllerAdvice class. You can read about it here. This way you can really handle the Exception, by returning a corresponding status code to the user. 503 in your case.
I know that the error handler middleware is like the final person who gives a very generic message to the user when things get wrong. Like return 500 server error.
But I think it's not helpful for the user. Once we catch an error in routes or middleware, it's better to give the user a more specific error message for a certain error.
So I don't think we should use error handler middleware in this case then? Am I right?
you can override the default error handler to give your users more specific error messages defined by you in your own custom error class
const { CustomAPIError } = require('../errors/customErrors');
const errorHandler = (error, req, res, next) => {
// for debugging purposes
console.log('[ERROR]: ', error);
if (error instanceof CustomAPIError)
return res.status(error.statusCode).json({message: error.message});
res.status(500).json({message: "Internal Server Error"});
}
module.exports = errorHandler;
As per Customizing Error Handling "Throwing the exception in the catch block will forward the message to the error queue. If that's not desired, remove the throw from the catch block to indicate that the message has been successfully processed." That's not true for me even if I simply swallow any kind of exception in a behavior:
public override async Task Invoke(IInvokeHandlerContext context, Func<Task> next)
{
try
{
await next().ConfigureAwait(false);
}
catch (Exception ex)
{
}
}
I put a breakpoint there and made sure execution hit the catch block. Nevertheless after intimidate and delayed retries messages inevitably ends up in error queue. And I have no more Behaviours in the pipeline besides this one.
Only if I run context.DoNotContinueDispatchingCurrentMessageToHandlers(); inside the catch block it prevents sending error to the error queue, but it also prevents any further immediate and delayed retries.
Any idea on why it works in contravention of Particular NserviceBus documentation is very appreciated
NserviceBus ver. used: 6.4.3
UPDATE:
I want only certain type of exceptions not being sent to an error queue in NServiceBus 6, however to make test case more clear and narrow down the root cause of an issue I use just type Exception. After throwing exception, execution certainly hits the empty catch block. Here is more code to that:
public class EndpointConfig : IConfigureThisEndpoint
{
public void Customize(EndpointConfiguration endpointConfiguration)
{
endpointConfiguration.DefineEndpointName("testEndpoint");
endpointConfiguration.UseSerialization<XmlSerializer>();
endpointConfiguration.DisableFeature<AutoSubscribe>();
configure
.Conventions()
.DefiningCommandsAs(t => t.IsMatched("Command"))
.DefiningEventsAs(t => t.IsMatched("Event"))
.DefiningMessagesAs(t => t.IsMatched("Message"));
var transport = endpointConfiguration.UseTransport<MsmqTransport>();
var routing = transport.Routing();
var rountingConfigurator = container.GetInstance<IRountingConfiguration>();
rountingConfigurator.ApplyRountingConfig(routing);
var instanceMappingFile = routing.InstanceMappingFile();
instanceMappingFile.FilePath("routing.xml");
transport.Transactions(TransportTransactionMode.TransactionScope);
endpointConfiguration.Pipeline.Register(
new CustomFaultMechanismBehavior(),
"Behavior to add custom handling logic for certain type of exceptions");
endpointConfiguration.UseContainer<StructureMapBuilder>(c => c.ExistingContainer(container));
var recoverability = endpointConfiguration.Recoverability();
recoverability.Immediate(immediate =>
{
immediate.NumberOfRetries(2);
});
endpointConfiguration.LimitMessageProcessingConcurrencyTo(16);
recoverability.Delayed(delayed =>
{
delayed.NumberOfRetries(2);
});
endpointConfiguration.SendFailedMessagesTo("errorQueue");
...
}
}
public class CustomFaultMechanismBehavior : Behavior<IInvokeHandlerContext>
{
public override async Task Invoke(IInvokeHandlerContext context, Func<Task> next)
{
try
{
await next().ConfigureAwait(false);
}
catch (Exception ex)
{
}
}
}
UPDATE 2
I think I know what's going on: message is handled by first handler that throws an exception which is caught by the Behavior catch block, but then NServiceBus runtime tries to instantiate second handler class which is also supposed to handle the message (it handles class the message is derived from). That's where another exception is thrown in a constructor of one of dependent class. StructureMap tries to instantiate the handler and all its dependent services declared in the constructor and in the process runs into the exception. And this exception is not caught by CustomFaultMechanismBehavior.
So my I rephrase my question now: Is there any way to suppress errors (ignore error queue) occurring inside constructor or simply during StructureMap classes initialization? Seems like the described way does not cover this kind of situations
Your behavior is activated on Handler invocation. This means you are catching exceptions happening inside the Handle method so any other exception, e.g. in the Constructor of the handler would not be caught.
To change the way you 'capture' the exceptions, you can change the way the behavior is activated, e.g. change it from Behavior<IInvokeHandlerContext> to Behavior<ITransportReceiveContext> which is activated when the transport receives a message. You can investigate on different stages and behaviors to see which one suits your purpose best.
I'm creating an HTTP API using ASP.NET Web API. I've noticed that if an exception occurs that I haven't handled, that behaviour is very different to if I deliberately throw an HttpResponseException. This will make it hard for clients to reliably handle an error and display the "reason" message.
Eg consider this code:
[HttpPost]
public void ThisWillThrowAnError()
{
try
{
var i = 0;
var b = 1 / i; // cause divide by zero exception for testing
}
catch (Exception ex)
{
HttpResponseMessage message = new HttpResponseMessage();
message.ReasonPhrase = "Error: " + ex.Message;
throw new HttpResponseException(message);
}
}
This creates a response which has the error in an HTTP header and the response code set to 500:
Error: This request could not be processed. Attempted to divide by zero.
The actual response body is empty.
However if I remove the try/catch block, or if an exception occurs for which I do not manually throw an HttpResponseException, I get totally different behaviour. Although the status code is still 500, the header message just says "Internal Server Error" and the message is encoded in a JSON format like this:
{
"Message": "An error has occurred.",
"ExceptionMessage": "Attempted to divide by zero.",
"ExceptionType": "System.DivideByZeroException",
"StackTrace": " at ProjectName.Controllers (etc....)"
}
I think I prefer the latter as it gives you more info for debugging but it removes the ability to customise the message or provide a user-readable message for the problem.
Why is WebAPI inconsistent with how it handles exceptions? Am I doing something myself to cause this inconsistency? It just seems rather messy and difficult to work with and may mean that the calling application will have to be coded to handle two different types of error response :(
When creating error responses, consider using HttpRequestMessage.CreateErrorResponse to create error responses that are consistent with the ones WebAPI sends.
This blog post should hopefully help:
http://blogs.msdn.com/b/youssefm/archive/2012/06/28/error-handling-in-asp-net-webapi.aspx
I would use message handlers. A message handler is a class that receives an HTTP request and returns an HTTP response. So you can basically change response structure in one place, and have same response for success and failure, and for all requests in your Web Api. You can read about it in my blog post: https://www.vladopandzic.com/asp-net-web-api/building-consistent-responses-asp-net-web-api/
I am trying to throw an HttpResponseException(HttpStatusCode.NotFound) and I am getting the following error
The response message returned by the Response property of this exception should be immediately returned to the client. No further handling of the request message is required.
I have removed all of the code in my method and I am just throwing the exception like this
[WebGet]
public MyData Get()
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
If I change my method to return a HttpResponseMessage I can get it to work correctly, however it does not solve the issue and I am unable to get my authentication operation handler to work without being able to throw a HttpResponseException.
Try using a WebFaultException for returning HTTP Status codes in WCF...
throw new WebFaultException(HttpStatusCode.NotFound);