Custom Exception Message in apex Salesforce - salesforce

I want to create a custom exception. In this exception I want to make a constructor which take one string arguments and append in getMessage .How to accomplish this.
public class TimelineException extends Exception{
private String message;
public override String getMessage(){
return 'Not able to post to Timeline.getting response from Api : '+ message;
}
}
Main problem I am facing is when I use this:
public TimelineException(Sting x){
}
then its give me error
Save error: System exception constructor already defined: (String) GMirror.cls /Google Salesforce Integration/src/classes.

You do not need to implement something. Just create a your exception class which would extends salesforce Exception class.
public class CommonException extends Exception {}
then just use it as other exception classes
try {
throw new CommonException('Test Common Exception');
} catch(CommonException ex) {
System.debug(ex.getMessage());
}
console output:
09:18:55:059 USER_DEBUG [4]|DEBUG|Test Common Exception

You can use something like this in your controller:
try
{
'content of what you tring to do'
}
catch(Exception e)
{
system.debug(e.getStackTraceString());
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'special friendly message to user'));
}
then in the visualForce page you write apex:messages/ where you want the message to be displayed

Related

PHP Fatal error: Class 'Message' not found - Google App Engine

I am using Google App Engine and am trying to send email alerts with the Mail PHP API. I have defined a class with a public function but whenever I run it I get this error:
PHP Fatal error: Class 'Message' not found in...
PHP Code:
use \google\appengine\api\mail\Message;
class crawls {
public function check() {
try {
$message = new Message();
$message->setSender('Name <test#domain.com>');
$message->addTo($recipients);
$message->setSubject('Subject');
$message->setHTMLBody("<p>Message</p>");
$message->send();
} catch (InvalidArgumentException $e) {
$error = "Unable to send mail. $e";
}
}
}
Everything works when I move the code outside of the class, but I want it inside the class.
Inherit Message class :
Define namespace if required.
class crawls extends \google\appengine\api\mail\Message {
// your code
}
Try this may it works for you:
class crawls {
public function check() {
try {
$message = new \google\appengine\api\mail\Message();
$message->setSender('Name <test#domain.com>');
$message->addTo($recipients);
$message->setSubject('Subject');
$message->setHTMLBody("<p>Message</p>");
$message->send();
} catch (InvalidArgumentException $e) {
$error = "Unable to send mail. $e";
}
}
}
Hope it helps

Can I suspend or resume a route based on a condition?

I want to be able to control programmatically a Route based on a condition but I cannot find a way to do it.
I don't want to stop the flow of a Route as in ProcessorDefinition.stop().
I tried to create a new RoutePolicy without any luck.
public class ProjectStateRoutePolicy extends RoutePolicySupport {
// this would be a check to an outside service
private boolean shouldStartRoute = false;
#Override
public void onStart(Route route) {
suspendIfNotInValidState(route);
}
#Override
public void onResume(Route route) {
suspendIfNotInValidState(route);
}
private void suspendIfNotInValidState(Route route) {
if ( !shouldStartRoute) {
try {
suspendRoute(route);
} catch (Exception e) {
throw ObjectHelper.wrapRuntimeCamelException(e);
}
}
}
}
According to my understanding onResume() and the like are CamelContext specific and not Route specific. Is there a fine-grained mechanism in place to have knowledge of a Route Lifecycle?
I want to be a able to control the lifecycle of the Route even if somene tries to start the Route manually e.g.from JMX.
PS: I don't think that Events such as RouteStartedEvent satisfy this constraint, since messages may have been consumed in between receiving and acting upon the event.
Here is some code that can do it, given you have the camel context and the route name.
public class StopRoute {
Logger log = LoggerFactory.getLogger(getClass().getName());
public void stop(CamelContext camelContext, String routeId) throws Exception {
log.info("Stopping camel route: " + routeId);
camelContext.stopRoute(routeId, 2, TimeUnit.SECONDS);
}
}
Similarly for StartRoute.
And then you can use it in your route like this:
.bean(StopRoute.class, "stop(*, " + INCOMING_SNAPSHOTS.routeId() + ")")
Hope this helps!
P.S. controlbus: essentially would do the same thing, as I understand ;)

Nancy testing GetModel<T> throws KeyNotFoundException

I'm trying to test that the model returned from my Nancy application is as expected. I have followed the docs here but whenever I call the GetModel<T> extension method it throws a KeyNotFoundException.
System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.
I know what the error means but I'm failing to see why it's being thrown.
Here's my module
public class SanityModule : NancyModule
{
public SanityModule()
{
Get["sanity-check"] = _ => Negotiate.WithModel(new SanityViewModel { Id = 1 })
.WithStatusCode(HttpStatusCode.OK);
}
}
my view model
public class SanityViewModel
{
public int Id { get; set; }
}
and here's my test
[TestFixture]
public class SanityModuleTests
{
[Test]
public void Sanity_Check()
{
// Arrange
var browser = new Browser(with =>
{
with.Module<SanityModule>();
with.ViewFactory<TestingViewFactory>();
});
// Act
var result = browser.Get("/sanity-check", with =>
{
with.HttpRequest();
with.Header("accept", "application/json");
});
var model = result.GetModel<SanityViewModel>();
// Asset
model.Id.ShouldBeEquivalentTo(1);
}
}
Debugging this test shows that the module is hit and completes just fine. Running the application shows that the response is as expected.
Can anyone shed some light on this?
Thanks to the lovely guys, albertjan and the.fringe.ninja, in the Nancy Jabbr room we've got an explanation as to what's going on here.
TL;DR It makes sense for this to not work but the error message should be more descriptive. There is a workaround below.
The issue here is that I am requesting the response as application/json whilst using TestingViewFactory.
Let's take a look at the implementation of GetModel<T>();
public static TType GetModel<TType>(this BrowserResponse response)
{
return (TType)response.Context.Items[TestingViewContextKeys.VIEWMODEL];
}
This is simply grabbing the view model from the NancyContext and casting it to your type. This is where the error is thrown, as there is no view model in NancyContext. This is because the view model is added to NancyContext in the RenderView method of TestingViewFactory.
public Response RenderView(string viewName, dynamic model, ViewLocationContext viewLocationContext)
{
// Intercept and store interesting stuff
viewLocationContext.Context.Items[TestingViewContextKeys.VIEWMODEL] = model;
viewLocationContext.Context.Items[TestingViewContextKeys.VIEWNAME] = viewName;
viewLocationContext.Context.Items[TestingViewContextKeys.MODULENAME] = viewLocationContext.ModuleName;
viewLocationContext.Context.Items[TestingViewContextKeys.MODULEPATH] = viewLocationContext.ModulePath;
return this.decoratedViewFactory.RenderView(viewName, model, viewLocationContext);
}
My test is requesting json so RenderView will not be called. This means you can only use GetModel<T> if you use a html request.
Workaround
My application is an api so I do not have any views so changing the line
with.Header("accept", "application/json");
to
with.Header("accept", "text/html");
will throw a ViewNotFoundException. To avoid this I need to implement my own IViewFactory. (this comes from the.fringe.ninja)
public class TestViewFactory : IViewFactory
{
#region IViewFactory Members
public Nancy.Response RenderView(string viewName, dynamic model, ViewLocationContext viewLocationContext)
{
viewLocationContext.Context.Items[Fixtures.SystemUnderTest.ViewModelKey] = model;
return new HtmlResponse();
}
#endregion
}
Then it is simply a case of updating
with.ViewFactory<TestingViewFactory>();
to
with.ViewFactory<TestViewFactory>();
Now GetModel<T> should work without needing a view.

throw an exception from org.apache.cxf.jaxrs.ext.RequestHandler handleRequest method

I have this problem using cxf dispatching behavior.
I have developed an Interceptor that implements the org.apache.cxf.jaxrs.ext.RequestHandler interface.
In its "public Response handleRequest(Message m, ClassResourceInfo resourceClass)" method I throw an exception (e.g. a WebServiceException) or a Fault. I have not apparent problems but, on the client side, the client receives a different exception (a ServerWebApplicationException) with the error message empty.
Here the code:
Server side:
public class RestInterceptor implements RequestHandler {
......
#Override
public Response handleRequest(Message m, ClassResourceInfo resourceClass){
.....
throw new WebServiceException("Failure in the dispatching ws invocation!");
.....
}
}
ServerWebApplicationException received on client side:
Status : 500
Headers :
Content-Length : 0
Connection : close
Server : Jetty(7.x.y-SNAPSHOT)
cause=null
detailMessage=null
errorMessage=""
.....
I received the same exception also if I throw a Fault.
What is the problem? I have to use another exception? Why?
Thanks a lot,
Andrea
OK, I've found the solution.I've registered an ExceptionMapper on the dispatcher and use it to encapsulate the exception inside the Response sent to the client.
To do this the interceptor is registered as provider at the web service publication and it implements the "ExceptionMapper" interface. In its "toResponse" method it encapsulates the exception in the Response.
Look at code:
public static<T extends Throwable> Response convertFaultToResponse(T ex, Message inMessage) {
ExceptionMapper<T> mapper = ProviderFactory.getInstance(inMessage).createExceptionMapper(ex.getClass(), inMessage);
if (mapper != null) {
try {
return mapper.toResponse(ex);
} catch (Exception mapperEx) {
mapperEx.printStackTrace();
return Response.serverError().build();
}
}
return null;
}
#Override
public Response toResponse(Exception arg0) {
ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR).type("application/xml");
String message = arg0.toString();
return builder.entity(message).build();
}
Andrea
Annotate your exception with #WebFault
example :
#WebFault(name = "oauthFault")
public class OAuthException extends RuntimeException {
...
}

Override model validate errors

I am new to CakePHP.
I would like to use the model validate mechanism, but I'm having trouble overriding the errors that are displayed. I am building an API where all the views need to be rendered in JSON and I have a JSON format that all errors need to output as. I've defined a custom AppError class and I have successfully be able to define custom errors in this format there.
Is there a way to use the AppError class to override the output of the error messages coming from validation?
Thanks.
I came up with a solution by adding these methods to my AppModel class:
function validates($options = array()) {
$result = parent::validates($options);
if (!$result) {
$this->_validateErrors();
}
return $result;
}
function _validateErrors() {
foreach ($this->validationErrors as $code) {
$this->cakeError('apiError', array('code' => $code)); // Custom JSON error.
return;
}
}
I then manually call $this->Model->validates() before a Model::save() call in my controller. This seems to be working well.
As far as I know, there's no direct way to get validation errors from within your AppError class. The way around it would be to create an AppModel class in app/app_model.php and use the onError() callback method to pass the error to your AppError class.
// app/app_model.php
class AppModel extends Model {
public function onError() {
// Pass the errors to your AppError class
AppError::someErrorMethod($this->getErrors());
}
}

Resources