Search Results

Search found 4116 results on 165 pages for 'baron throw'.

Page 4/165 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Get Python 2.7's 'json' to not throw an exception when it encounters random byte strings

    - by Chris Dutrow
    Trying to encode a a dict object into json using Python 2.7's json (ie: import json). The object has some byte strings in it that are "pickled" data using cPickle, so for json's purposes, they are basically random byte strings. I was using django.utils's simplejson and this worked fine. But I recently switched to Python 2.7 on google app engine and they don't seem to have simplejson available anymore. Now that I am using json, it throws an exception when it encounters bytes that aren't part of UTF-8. The error that I'm getting is: UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 0: invalid start byte It would be nice if it printed out a string of the character codes like the debugging might do, ie: \u0002]q\u0000U\u001201. But I really don't much care how it handles this data just as long as it doesn't throw an exception and continues serializing the information that it does recognize. How can I make this happen? Thanks!

    Read the article

  • Unity 2.0. How to throw ResolutionFailedException

    - by Andrey Khataev
    Hello, I have my app, using functionality that is based on unity application block. Sometimes I need to throw ResolutionFailedException manually. In v1.2 constructor of ResolutionFailedException had three parameters - typerequested, namerequested and exception. In v2.0 fourth parameter was added - buildercontext. I'm not creating it manually, so I have no reference to it and no idea where I can get it. Roughly speaking, I'm only overriding Resolve method in particular way and I'm not interfere in standard mechanism of policies, strategies and so on. Could anyone help?

    Read the article

  • Throw blank even-numbered/left pages

    - by TimGJ
    I am trying to typeset a large document using ReportLab and Python 2.7. It has a number of sections (about 6 in a 1,000 page document) and I would like each to start on odd-numbered/right-hand page. I have no idea though whether the preceding page will be odd or even and so need the ability to optionally throw an additional blank page before a particular paragraph style (like you sometimes get in manuals where some pages are "intentionally left blank"). Can anyone suggest how this could be done, as the only conditional page break I can find works on the basis of the amount of text on the page not a page number. I also need to make sure that the blank page is included in the PDF so that double-sided printing works.

    Read the article

  • Does 'throw' or 'try...catch' hinder performance?

    - by Richard
    I've been reading all over the place (including here) about when exception should / shouldn't be used. I now want to change my code that would throw to make the method return false and handle it like that, but my question is: Is it the throwing or try..catch-ing that can hinder performance...? What I mean is, would this be acceptable: bool method someMmethod() { try { // ...Do something catch (Exception ex) // Don't care too much what at the moment... { // Output error // Return false } return true // No errors Or would there be a better way to do it? (I'm bloody sick of seeing "Unhandled exception..." LOL!)

    Read the article

  • Exception throws: encapsulate them or not?

    - by Simon
    Hi there. Once I read an MSDN article that encouraged the following programming paradigm: public class MyClass { public void Method1() { NewCustomException(); } public void Method2() { NewCustomException(); } void NewCustomException() { throw new CustomException("Exception message"); } } Do you think this paradigm makes sense? Wouldn't it be enough to store the exception message in a static const field and then pass it to the exception's constructor, instead of encapsulating the whole exception throw?

    Read the article

  • How can this code throw a NullReferenceException?

    - by Davy8
    I must be going out of my mind, because my unit tests are failing because the following code is throwing a null ref exception: int pid = 0; if (parentCategory != null) { Console.WriteLine(parentCategory.Id); pid = parentCategory.Id; } The line that's throwing it is: pid = parentCategory.Id; The console.writeline is just to debug in the NUnit GUI, but that outputs a valid int. Edit: It's single-threaded so it can't be assigned to null from some other thread, and the fact the the Console.WriteLine successfully prints out the value shows that it shouldn't throw. Edit: Relevant snippets of the Category class: public class Category { private readonly int id; public Category(Category parent, int id) { Parent = parent; parent.PerformIfNotNull(() => parent.subcategories.AddIfNew(this)); Name = string.Empty; this.id = id; } public int Id { get { return id; } } } Well if anyone wants to look at the full code, it's on Google Code at http://code.google.com/p/chefbook/source/checkout I think I'm going to try rebooting the computer... I've seen pretty weird things fixed by a reboot. Will update after reboot. Update: Mystery solved. Looks like NUnit shows the error line as the last successfully executed statement... Copy/pasted test into new console app and ran in VS showed that it was the line after the if statement block (not shown) that contained a null ref. Thanks for all the ideas everyone. +1 to everyone that answered.

    Read the article

  • Initialising vals which might throw an exception

    - by Paul Butcher
    I need to initialise a set of vals, where the code to initialise them might throw an exception. I'd love to write: try { val x = ... generate x value ... val y = ... generate y value ... } catch { ... exception handling ... } ... use x and y ... But this (obviously) doesn't work because x and y aren't in scope outside of the try. It's easy to solve the problem by using mutable variables: var x: Whatever = _ var y: Whatever = _ try { x = ... generate x value ... y = ... generate y value ... } catch { ... exception handling ... } ... use x and y ... But that's not exactly very nice. It's also easy to solve the problem by duplicating the exception handling: val x = try { ... generate x value ... } catch { ... exception handling ... } val y = try { ... generate y value ... } catch { ... exception handling ... } ... use x and y ... But that involves duplicating the exception handling. There must be a "nice" way, but it's eluding me.

    Read the article

  • Glassfish4 throw exception when I declare validation.xml file on classpath

    - by Rafael Ruiz Tabares
    I've tried to declare a custom validator for @NotNull constraint and Glassfish4 throw this exception when find /META-INF/validation.xml. Project works fine if I omit this file. Exception while dispatching an event java.lang.IllegalStateException: Singleton not set for WebappClassLoader(delegate=true; repositories=WEB-INF/classes/) at org.glassfish.weld.ACLSingletonProvider$ACLSingleton.get(ACLSingletonProvider.java:110) at org.jboss.weld.Container.instance(Container.java:54) at org.jboss.weld.bootstrap.WeldBootstrap.shutdown(WeldBootstrap.java:644) at org.glassfish.weld.WeldDeployer.doBootstrapShutdown(WeldDeployer.java:309) at org.glassfish.weld.WeldDeployer.event(WeldDeployer.java:220) at org.glassfish.kernel.event.EventsImpl.send(EventsImpl.java:131) at org.glassfish.internal.data.ApplicationInfo.load(ApplicationInfo.java:328) at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:493) at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219) at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491) at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:527) at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:523) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:356) at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:522) at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:546) at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1423) at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1500(CommandRunnerImpl.java:108) at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1762) at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1674) at org.glassfish.admin.rest.resources.admin.CommandResource.executeCommand(CommandResource.java:396) at org.glassfish.admin.rest.resources.admin.CommandResource.execCommandSimpInMultOut(CommandResource.java:234) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:125) at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:152) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:91) at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:346) at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:341) at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:101) at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:224) at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271) at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267) at org.glassfish.jersey.internal.Errors.process(Errors.java:315) at org.glassfish.jersey.internal.Errors.process(Errors.java:297) at org.glassfish.jersey.internal.Errors.process(Errors.java:267) at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317) at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:198) at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:946) at org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpContainer.service(GrizzlyHttpContainer.java:331) at org.glassfish.admin.rest.adapter.JerseyContainerCommandService$3.service(JerseyContainerCommandService.java:165) at org.glassfish.admin.rest.adapter.RestAdapter.service(RestAdapter.java:181) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:246) at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191) at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168) at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189) at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206) at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136) at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114) at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77) at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838) at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544) at java.lang.Thread.run(Thread.java:744) ]] [2014-06-09T19:37:52.476+0200] [glassfish 4.0] [SEVERE] [AS-WEB-CORE-00108] [javax.enterprise.web.core] [tid: _ThreadID=32 _ThreadName=admin-listener(1)] [timeMillis: 1402335472476] [levelValue: 1000] [[ ContainerBase.addChild: start: org.apache.catalina.LifecycleException: java.lang.IllegalArgumentException: javax.servlet.ServletException: com.sun.enterprise.container.common.spi.util.InjectionException: Error creating managed object for class: class org.jboss.weld.servlet.WeldListener at org.apache.catalina.core.StandardContext.start(StandardContext.java:5864) at com.sun.enterprise.web.WebModule.start(WebModule.java:691) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:1041) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:1024) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:747) at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:2278) at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:1924) at com.sun.enterprise.web.WebApplication.start(WebApplication.java:139) at org.glassfish.internal.data.EngineRef.start(EngineRef.java:122) at org.glassfish.internal.data.ModuleInfo.start(ModuleInfo.java:291) at org.glassfish.internal.data.ApplicationInfo.start(ApplicationInfo.java:352) at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:497) at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219) at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491) at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:527) at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:523) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:356) at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:522) at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:546) at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1423) at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1500(CommandRunnerImpl.java:108) at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1762) at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1674) at org.glassfish.admin.rest.resources.admin.CommandResource.executeCommand(CommandResource.java:396) at org.glassfish.admin.rest.resources.admin.CommandResource.execCommandSimpInMultOut(CommandResource.java:234) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:125) at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:152) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:91) at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:346) at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:341) at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:101) at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:224) at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271) at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267) at org.glassfish.jersey.internal.Errors.process(Errors.java:315) at org.glassfish.jersey.internal.Errors.process(Errors.java:297) at org.glassfish.jersey.internal.Errors.process(Errors.java:267) at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317) at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:198) at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:946) at org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpContainer.service(GrizzlyHttpContainer.java:331) at org.glassfish.admin.rest.adapter.JerseyContainerCommandService$3.service(JerseyContainerCommandService.java:165) at org.glassfish.admin.rest.adapter.RestAdapter.service(RestAdapter.java:181) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:246) at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191) at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168) at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189) at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206) at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136) at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114) at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77) at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838) at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544) at java.lang.Thread.run(Thread.java:744) Caused by: java.lang.IllegalArgumentException: javax.servlet.ServletException: com.sun.enterprise.container.common.spi.util.InjectionException: Error creating managed object for class: class org.jboss.weld.servlet.WeldListener at org.apache.catalina.core.StandardContext.addListener(StandardContext.java:3270) at org.apache.catalina.core.StandardContext.addApplicationListener(StandardContext.java:2476) at com.sun.enterprise.web.TomcatDeploymentConfig.configureApplicationListener(TomcatDeploymentConfig.java:251) at com.sun.enterprise.web.TomcatDeploymentConfig.configureWebModule(TomcatDeploymentConfig.java:110) at com.sun.enterprise.web.WebModuleContextConfig.start(WebModuleContextConfig.java:266) at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:486) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:163) at org.apache.catalina.core.StandardContext.start(StandardContext.java:5861) ... 66 more Caused by: javax.servlet.ServletException: com.sun.enterprise.container.common.spi.util.InjectionException: Error creating managed object for class: class org.jboss.weld.servlet.WeldListener at org.apache.catalina.core.StandardContext.createListener(StandardContext.java:3391) at org.apache.catalina.core.StandardContext.loadListener(StandardContext.java:5414) at com.sun.enterprise.web.WebModule.loadListener(WebModule.java:1788) at org.apache.catalina.core.StandardContext.addListener(StandardContext.java:3268) ... 73 more Caused by: com.sun.enterprise.container.common.spi.util.InjectionException: Error creating managed object for class: class org.jboss.weld.servlet.WeldListener at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.createManagedObject(InjectionManagerImpl.java:329) at com.sun.enterprise.web.WebContainer.createListenerInstance(WebContainer.java:1015) at com.sun.enterprise.web.WebModule.createListenerInstance(WebModule.java:2158) at org.apache.catalina.core.StandardContext.createListener(StandardContext.java:3389) ... 76 more Caused by: java.lang.NullPointerException at org.jboss.weld.bootstrap.WeldBootstrap.getManager(WeldBootstrap.java:435) at org.glassfish.weld.services.JCDIServiceImpl.createManagedObject(JCDIServiceImpl.java:320) at org.glassfish.weld.services.JCDIServiceImpl.createManagedObject(JCDIServiceImpl.java:263) at com.sun.enterprise.container.common.impl.managedbean.ManagedBeanManagerImpl.createManagedBean(ManagedBeanManagerImpl.java:485) at com.sun.enterprise.container.common.impl.managedbean.ManagedBeanManagerImpl.createManagedBean(ManagedBeanManagerImpl.java:439) at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.createManagedObject(InjectionManagerImpl.java:313) ... 79 more This is constraint xml file <constraint-definition annotation="org.hibernate.validator.constraints.NotNull"> <validated-by include-existing-validators="true"> <value>es.project.validator.customConstraint.NotEmptyValidator</value> </validated-by> </constraint-definition> And validation.xml <validation-config xmlns="http://jboss.org/xml/ns/javax/validation/configuration" xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/configuration validation-configuration-1.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <constraint-mapping>META-INF/validation/mapping.xml</constraint-mapping> Project's structure WEB-INF +----\classes +-------\META-INF ------- validation.xml ----------\validation +----------\mapping.xml Validator code import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorContext; public class NotEmptyValidator implements ConstraintValidator<NotNull,Object> { @Override public void initialize(NotNull constraintAnnotation) { } @Override public boolean isValid(Object value, ConstraintValidatorContext context) { if(value.toString().isEmpty()){ ........... ........... ........... } return true; } }

    Read the article

  • If the model is validating the data, shouldn't it throw exceptions on bad input?

    - by Carlos Campderrós
    Reading this SO question it seems that throwing exceptions for validating user input is frowned upon. But who should validate this data? In my applications, all validations are done in the business layer, because only the class itself really knows which values are valid for each one of its properties. If I were to copy the rules for validating a property to the controller, it is possible that the validation rules change and now there are two places where the modification should be made. Is my premise that validation should be done on the business layer wrong? What I do So my code usually ends up like this: <?php class Person { private $name; private $age; public function setName($n) { $n = trim($n); if (mb_strlen($n) == 0) { throw new ValidationException("Name cannot be empty"); } $this->name = $n; } public function setAge($a) { if (!is_int($a)) { if (!ctype_digit(trim($a))) { throw new ValidationException("Age $a is not valid"); } $a = (int)$a; } if ($a < 0 || $a > 150) { throw new ValidationException("Age $a is out of bounds"); } $this->age = $a; } // other getters, setters and methods } In the controller, I just pass the input data to the model, and catch thrown exceptions to show the error(s) to the user: <?php $person = new Person(); $errors = array(); // global try for all exceptions other than ValidationException try { // validation and process (if everything ok) try { $person->setAge($_POST['age']); } catch (ValidationException $e) { $errors['age'] = $e->getMessage(); } try { $person->setName($_POST['name']); } catch (ValidationException $e) { $errors['name'] = $e->getMessage(); } ... } catch (Exception $e) { // log the error, send 500 internal server error to the client // and finish the request } if (count($errors) == 0) { // process } else { showErrorsToUser($errors); } Is this a bad methodology? Alternate method Should maybe I create methods for isValidAge($a) that return true/false and then call them from the controller? <?php class Person { private $name; private $age; public function setName($n) { $n = trim($n); if ($this->isValidName($n)) { $this->name = $n; } else { throw new Exception("Invalid name"); } } public function setAge($a) { if ($this->isValidAge($a)) { $this->age = $a; } else { throw new Exception("Invalid age"); } } public function isValidName($n) { $n = trim($n); if (mb_strlen($n) == 0) { return false; } return true; } public function isValidAge($a) { if (!is_int($a)) { if (!ctype_digit(trim($a))) { return false; } $a = (int)$a; } if ($a < 0 || $a > 150) { return false; } return true; } // other getters, setters and methods } And the controller will be basically the same, just instead of try/catch there are now if/else: <?php $person = new Person(); $errors = array(); if ($person->isValidAge($age)) { $person->setAge($age); } catch (Exception $e) { $errors['age'] = "Invalid age"; } if ($person->isValidName($name)) { $person->setName($name); } catch (Exception $e) { $errors['name'] = "Invalid name"; } ... if (count($errors) == 0) { // process } else { showErrorsToUser($errors); } So, what should I do? I'm pretty happy with my original method, and my colleagues to whom I have showed it in general have liked it. Despite this, should I change to the alternate method? Or am I doing this terribly wrong and I should look for another way?

    Read the article

  • WebClient on WP7 - Throw "A request with this method cannot have a request body"

    - by Peter Hansen
    If I execute this code in a Consoleapp it works fine: string uriString = "http://url.com/api/v1.0/d/" + Username + "/some?amount=3&offset=0"; WebClient wc = new WebClient(); wc.Headers["Content-Type"] = "application/json"; wc.Headers["Authorization"] = AuthString.Replace("\\", ""); string responseArrayKvitteringer = wc.DownloadString(uriString); Console.WriteLine(responseArrayKvitteringer); But if I move the code to my WP7 project like this: string uriString = "http://url.com/api/v1.0/d/" + Username + "/some?amount=3&offset=0"; WebClient wc = new WebClient(); wc.Headers["Content-Type"] = "application/json"; wc.Headers["Authorization"] = AuthString.Replace("\\", ""); wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted); wc.DownloadStringAsync(new Uri(uriString)); void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { MessageBox.Show(e.Result); } I got the exception: A request with this method cannot have a request body. Why? The solution is to remove the Content-type: string uriString = "http://url.com/api/v1.0/d/" + Username + "/some?amount=3&offset=0"; WebClient wc = new WebClient(); //wc.Headers["Content-Type"] = "application/json"; wc.Headers["Authorization"] = AuthString.Replace("\\", ""); wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted); wc.DownloadStringAsync(new Uri(uriString)); void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { MessageBox.Show(e.Result); }

    Read the article

  • android throw InvocationTargetException,How to modify the error

    - by fonter
    ActivityManager am = (ActivityManager)this.getSystemService(this.ACTIVITY_SERVICE); try { clearMethod = am.getClass() .getMethod("clearApplicationUserData", String.class, IPackageDataObserver.class); } catch (Exception e) { Log.e("Error", "Android Error",e); clearMethod = null; } if(clearMethod!=null){ try { clearMethod.invoke(am,"com.android.browser",new ClearUserDataObserver()); } catch (Exception e) { Log.e("Error", "Android Exception",e); } } Exception 05-26 08:34:13.056: ERROR/Error(739): java.lang.reflect.InvocationTargetException 05-26 08:34:13.056: ERROR/Error(739): at android.app.ActivityManager.clearApplicationUserData(ActivityManager.java:475) 05-26 08:34:13.056: ERROR/Error(739): at java.lang.reflect.Method.invokeNative(Native Method) 05-26 08:34:13.056: ERROR/Error(739): at java.lang.reflect.Method.invoke(Method.java:521) 05-26 08:34:13.056: ERROR/Error(739): at com.iwidsets.clear.manager.AndClear.onCreate(AndClear.java:34) 05-26 08:34:13.056: ERROR/Error(739): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123) 05-26 08:34:13.056: ERROR/Error(739): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364) 05-26 08:34:13.056: ERROR/Error(739): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2417) 05-26 08:34:13.056: ERROR/Error(739): at android.app.ActivityThread.access$2100(ActivityThread.java:116) 05-26 08:34:13.056: ERROR/Error(739): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794) 05-26 08:34:13.056: ERROR/Error(739): at android.os.Handler.dispatchMessage(Handler.java:99) 05-26 08:34:13.056: ERROR/Error(739): at android.os.Looper.loop(Looper.java:123) 05-26 08:34:13.056: ERROR/Error(739): at android.app.ActivityThread.main(ActivityThread.java:4203) 05-26 08:34:13.056: ERROR/Error(739): at java.lang.reflect.Method.invokeNative(Native Method) 05-26 08:34:13.056: ERROR/Error(739): at java.lang.reflect.Method.invoke(Method.java:521) 05-26 08:34:13.056: ERROR/Error(739): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791) 05-26 08:34:13.056: ERROR/Error(739): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549) 05-26 08:34:13.056: ERROR/Error(739): at dalvik.system.NativeStart.main(Native Method) 05-26 08:34:13.056: ERROR/Error(739): Caused by: java.lang.SecurityException: 739 does not have permission:android.permission.CLEAR_APP_USER_DATA to clear datafor process:com.android.browser 05-26 08:34:13.056: ERROR/Error(739): at android.os.Parcel.readException(Parcel.java:1218) 05-26 08:34:13.056: ERROR/Error(739): at android.os.Parcel.readException(Parcel.java:1206) 05-26 08:34:13.056: ERROR/Error(739): at android.app.ActivityManagerProxy.clearApplicationUserData(ActivityManagerNative.java:2016) 05-26 08:34:13.056: ERROR/Error(739): ... 17 more

    Read the article

  • Why does GetSqlDecimal throw when GetDecimal doesn't?

    - by I. J. Kennedy
    I have a database table that has a column of type money, allowing nulls. Using a SqlDataReader named reader, I can do decimal d = reader.GetDecimal(1); which works, unless of course we're reading a null. If I try using SqlDecimal instead--and I thought the whole point of the SqlTypes was to deal with nulls--then I get an invalid cast, whether or not the value is null. SqlDecimal s = reader.GetSqlDecimal(1); // throws an invalid cast exception What am I doing wrong? Do I really have to write a conditional statement to shepherd the value from the database to a SqlDecimal variable?

    Read the article

  • Why does System.Web.Hosting.ApplicationHost.CreateApplicationHost throw System.IO.FileNotFoundExcept

    - by Scott Langham
    I saw something about needing to have the assembly available for the type of the first argument passed to the function. I think it is, I can't figure out what am I missing. This code is in a service. I was running the service under the 'NETWORK SERVICES' user account, when I changed the account to that of the session I was logged on with it worked ok. But, what's the difference, and how can I get it to work for the NETWORK SERVICES user.

    Read the article

  • Why does UIWebKit throw a structuralComplexityContribution exception?

    - by Axeva
    I've got a simple UIWebView in my iPhone app that's loading a XHTML document with some SGV embeded. This all works find on the desktop version of Safari, but it crashes in a UIWebView. Here is the Objective C: NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"html"]; NSData *fileData = [NSData dataWithContentsOfFile: path]; [svgView loadData: fileData MIMEType: @"text/xml" textEncodingName: @"UTF-8" baseURL: [NSURL fileURLWithPath: path]]; I also tried a MIMEType of application/xhtml+xml, but it didn't help. Here is the HTML: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>XTech SVG Demo</title> </head> <body> <svg xmlns="http://www.w3.org/2000/svg"> <g style="fill-opacity:0.7;"> <circle cx="6.5cm" cy="2cm" r="100" style="fill:red; stroke:black; stroke-width:0.1cm" transform="translate(0,50)" /> <circle cx="6.5cm" cy="2cm" r="100" style="fill:blue; stroke:black; stroke-width:0.1cm" transform="translate(70,150)" /> <circle cx="6.5cm" cy="2cm" r="100" style="fill:green; stroke:black; stroke-width:0.1cm" transform="translate(-70,150)"/> </g> </svg> </body> </html> All very basic stuff. When it loads on the iPhone, however, it crashes with this error: 2010-03-31 10:37:10.252 ColorDoodle[2014:20b] -[DOMElement structuralComplexityContribution]: unrecognized selector sent to instance 0x3e51b60 2010-03-31 10:37:10.253 ColorDoodle[2014:20b] Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: ' -[DOMElement structuralComplexityContribution]: unrecognized selector sent to instance 0x3e51b60' Any idea why? Is this a bug in the rendering engine of the UIWebView? I don't see anything too odd here. * Updated * There is definitely something screwy going on here. If I add this bit of code just inside the tag, it works fine: <form> </form> Take that code back out, and it crashes again.

    Read the article

  • Embedded Javascript in Master Page or Pages That Use Master Page throw "Object Expected Error"

    - by Philter
    I'm semi-new to writing ASP.Net applications using master pages and I've run into an issue I've spent some time on but can't seem to solve. My situation is that I have a master page with a structure that looks like this: <head runat="server"> <title>Test Site</title> <link rel="Stylesheet" type="text/css" href="Default.css" /> <script type="text/javascript" language="javascript" src="js/Default.js" /> <meta http-equiv="Expires" content="0"/> <meta http-equiv="Cache-Control" content="no-cache"/> <meta http-equiv="Pragma" content="no-cache"/> <asp:ContentPlaceHolder ID="cphHead" runat="server"> </asp:ContentPlaceHolder> </head> <body> <form id="form1" runat="server"> <div id="divHeader"> <asp:ContentPlaceHolder ID="cphPageTitle" runat="server"></asp:ContentPlaceHolder> </div> <div id="divMainContent"> <asp:ContentPlaceHolder ID="cphMainContent" runat="server"></asp:ContentPlaceHolder> </div> </div> </form> </body> I then have a page that uses this master page that contains the following: <asp:Content ContentPlaceHolderID="cphHead" runat="server"> <script type="text/javascript" language="javascript" > function test() { alert("Hello World"); } </script> </asp:Content> <asp:Content ContentPlaceHolderID="cphMainContent" runat="server"> <fieldset> <img alt="Select As Of Date" src="Images/Calendar.png" id="aAsOfDate" class="clickable" runat="server" onclick="test();" /> <asp:Button runat="server" CssClass="buttonStyle" ID="btnSubmit" Text="Submit" OnClick="btnSubmit_Clicked"/> </fieldset> </asp:Content> When I run this page and click on the image I get an "Object Expected" error. However, if I place the test function into my Default.js external file it will function perfectly. I can't seem to figure out why this is happening. Any ideas?

    Read the article

  • One class instance throw all controller

    - by Falcon
    Hello i i have different class and controller. and i need that one instance of model will be available in controller/ now i'm doing something like this: def method1 inst = @MyClass.new(params) inst.action .... def method2 inst = @MyClass.new(params) inst.action .... but i want something like this def method1 @inst.action .... def method2 @inst.action or self.inst i't doesn't matter how i can do it? def self.inst MyClass.new(params) end doesn't work...

    Read the article

  • Visual Studio 2010 failed tests throw exceptions

    - by Dave Hanson
    In VisualStudio2010 Ultimate RC I cannot figure out how to suppress {"CollectionAssert.AreEqual failed. (Element at index 0 do not match.)"} from Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException If i Ctrl+Alt+E I get the exception dialog; however that exception doesn't seem to be in there to be suppressed. Does anyone else have any experience with this? I don't remember having to suppress these Assert fails in studio 2008 when running unit tests. My tests would fail and I could just click on the TestResults to see which tests failed instead of fighting through these dialogs. For now I guess I'll just run my tests through the command window.

    Read the article

  • .toggle(true) throw null in $(document).ready(function())

    - by James123
    I am toggling row siblings. I wrote .toggle(true) when document ready. see below picture. I think row sibling are not availble before this function calls. $(document).ready(function() { $('tr[@class^=RegText]').hide().children('td'); list_Visible_Ids = []; var idsString, idsArray; idsString = $('#myVisibleRows').val(); idsArray = idsString.split(','); $.each(idsArray, function() { if (this != "") { $(this).siblings('.RegText').toggle(true); list_Visible_Ids[this] = 1; } }); How to resolve this? why sliblings are not avaible in when document is ready?

    Read the article

  • Zero division does not throw exception in nunit

    - by Boris
    Running the following C# code through NUnit yields Test.ControllerTest.TestSanity: Expected: <System.DivideByZeroException> But was: null So either no DivideByZeroException is thrown, or NUnit does not catch it. Similar to this question, but the answers he got, do not seem to work for me. This is using NUnit 2.5.5.10112, and .NET 4.0.30319. [Test] public void TestSanity() { Assert.Throws<DivideByZeroException>(new TestDelegate(() => DivideByZero())); } private void DivideByZero() { // Parse "0" to make sure to get an error at run time, not compile time. var a = (1 / Double.Parse("0")); } Any ideas?

    Read the article

  • Native functions throw UnsatisfiedLinkError in custom view, despite working in main activity

    - by Mark Ingram
    For some reason I can only call native functions from my main activity and not any custom views that I've created. Here is an example file (I followed a tutorial, but renamed the classes http://mindtherobot.com/blog/452/android-beginners-ndk-setup-step-by-step/) See the usage of the native function "getNewString". package com.example.native; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.os.Bundle; import android.view.View; public class NativeTestActivity extends Activity { static { System.loadLibrary("nativeTest"); } private native String getNewString(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(new BitmapView(this)); String hello = getNewString(); // This line works fine new AlertDialog.Builder(this).setMessage(hello).show(); } } class BitmapView extends View { static { System.loadLibrary("nativeTest"); } private native String getNewString(); public BitmapView(Context context) { super(context); String hello = getNewString(); // This line throws the UnsatisfiedLinkError new AlertDialog.Builder(this.getContext()).setMessage(hello).show(); } } How can I call native functions in my custom views? I've built the application as an Android 2.2 app. I'm running the application on my HTC Desire. I have the latest SDK (9) and latest NDK (r5).

    Read the article

  • Cast MyEntity To LinqEntity throw a base controller class

    - by Mohammad Kani
    hi there i design a multilayer we appliction andusing LINQ a my data provider i need to user my own Entites instead o LINQ etities. so i created Entities Project and create my entities in it. when i get data from contex and cast them to my entities , everything is ok. but when i want to cast on of my entities to linq entity , an exception thrown. in my linq entity i add CTYPE operator from and to my entities Exp : Public Class BaseController(Of LinqEntity As {BaseEntity, New}, MyEntity As ModuleEntities.BaseEntityInfo) Implements Interfaces.Base(Of ServiceEntity) 'This methd work fine and cast LinqEntity to MyEntity Public Function GetAll() As List(Of MyEntity ) Dim q = (From x In Context.GetTable(Of LinqEntity)() _ Select x).Cast(Of MyEntityBase) End Function Public Sub Update(ByVal entity As MyEntity) 'here is problem 'cast , direct cast , or anything not work Dim x as LinqEntity = entity Me.Context.GetTable(Of LinqEntity).InsertOnSubmit(entity) Me.Context.SubmiChanges() End Sub

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >