Error Handling In Spring Mvc 3.0
App EngineApache AntApache MavenjQueryJava MongoDBQuartz SchedulerLog4jContact Us Spring MVC @ExceptionHandler ExampleBy mkyong | October 7, 2013 | Viewed : 136,533 times +1,036 pv/wIn this tutorial, we show you how to do exception handling in Spring MVC frameworks. Normally, we use @ExceptionHandler to decide which "view" should be returned back if certain exception is raised.P.S This @ExceptionHandler class is available since Spring 3.01. Project StructureReview the project directory structure, a standard Maven project. 2. Custom ExceptionA custom exception, with custom error code and error description.CustomGenericException.java package com.mkyong.web.exception; public class CustomGenericException extends RuntimeException { private static final long serialVersionUID = 1L; private String errCode; private String errMsg; public String getErrCode() { return errCode; } public void setErrCode(String errCode) { this.errCode = errCode; } public String getErrMsg() { return errMsg; } public void setErrMsg(String errMsg) { this.errMsg = errMsg; } public CustomGenericException(String errCode, String errMsg) { this.errCode = errCode; this.errMsg = errMsg; } } 3. Spring ControllerA Spring controller, review the execution-flows below :If user provide a /error request, it throws "CustomGenericException", and the handleCustomException() method will be fired. If user provide a /io-error request, it throws "IOException", and the handleAllException() method will be fired.MainController.java package com.mkyong.web.controller; import java.io.IOException; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.mkyong.web.exception.CustomGenericException; @Controller public class MainController { @RequestMapping(value = "/{type:.+}", method = RequestMethod.GET) public ModelAndView getPages(@PathVariable("type") String type) throws Exception { if ("error".equals(type)) { // go handleCustomException throw new CustomGenericException("E888", "This i
Environment Setup Spring - Hello World Example Spring - IoC Containers Spring - Bean Definition Spring - Bean Scopes Spring - Bean Life Cycle Spring - Bean Post Processors Spring - Bean Definition Inheritance Spring - Dependency Injection Spring - Injecting Inner Beans Spring - Injecting Collection Spring - Beans Auto-Wiring Annotation Based Configuration Spring - Java Based Configuration Spring - Event Handling in Spring Spring - Custom Events in Spring Spring - AOP with Spring Framework Spring https://www.mkyong.com/spring-mvc/spring-mvc-exceptionhandler-example/ - JDBC Framework Spring - Transaction Management Spring - Web MVC Framework Spring - Logging with Log4J Spring Questions and Answers Spring - Questions and Answers Spring Useful Resources Spring - Quick Guide Spring - Useful Resources Spring - Discussion Selected Reading Developer's Best Practices Questions and Answers Effective Resume Writing HR Interview Questions Computer Glossary Who https://www.tutorialspoint.com/spring/spring_exception_handling_example.htm is Who Spring - Exception Handling Example Advertisements Previous Page Next Page The following example show how to write a simple web based application using Spring MVC Framwork, which can handle one or more exceptions raised inside its controllers. To start with it, let us have working Eclipse IDE in place and follow the following steps to develope a Dynamic Form based Web Application using Spring Web Framework: StepDescription 1Create a Dynamic Web Project with a name HelloWeb and create a package com.tutorialspoint under the src folder in the created project. 2Drag and drop below mentioned Spring and other libraries into the folder WebContent/WEB-INF/lib. 3Create a Java classes Student, StudentController and SpringException under the com.tutorialspoint package. 4Create Spring configuration files Web.xml and HelloWeb-servlet.xml under the WebContent/WEB-INF folder. 5Create a sub-folder with a name jsp under the WebContent/WEB-INF folder. Create a view files student.jsp, result.jsp, error.jsp, and ExceptionPage.jsp under jsp sub-folder. 6The final step is to create the content of all the source and configuration files
and DropEventsExpandableListViewGridViewHorizontalScrollViewImageButtonImageViewLinearLayoutListViewNotificationsPasswordProgressBarProgressDialogRadioButtonRadioGroupRatingBarRelativeLayoutScrollViewSelectorSettingsSpinnerSurfaceViewTextBoxTimePickerToastToggleButtonWebViewviewMenuOnClickListenerViewPagerwidgetAutoCompleteTextViewEditTextFrameLayoutSeekBarSlidingDrawerStackViewTextViewViewFlipperxmlgamescanvasmain loopOpenGL ESCore JavaanimationapacheANTcommonsbeanutilsconvertersArrayConvertercliBasicParsercodecbinaryBase64Base64OutputStreamcsvdbcpBasicDatasourcePoolingConnectioniocomparatorCompositeFileComparatorDirectoryFileComparatorLastModifiedFileComparatorNameFileComparatorPathFileComparatorFilenameUtilsFileUtilsIOUtilsmonitorFileAlterationMonitorlang3CharUtilsClassPathUtilsmathFractionNumberUtilsStringUtilsloggingLogfactorynetCookieStoreFTPClientURLClassLoaderURLConnectionluceneappletaspectjbeanscajoCharacterclassComperablecryptoDesign PatternsdecoratorstrategyGenericsGradlegsonGsonBuilderstreamJsonReaderJsonWriterioBufferedInputStreamBufferedOutputStreamBufferedReaderBufferedWriterByteArrayInputStreamByteArrayOutputStreamConsoleDataInputStreamDataOutputStreamExternalizableFileFileDescriptorFileInputStreamFilenameFilterFileOutputStreamFileReaderFileWriterInputStreamInputStreamReaderIOExceptionObjectInputStreamObjectOutputStreamOutputStreamPrintWriterRandomAccessFileSerializableStreamTokenizerStringReaderStringWriterjsonJacksonJSON.SimplejunitlangmanagementNumberFormatExceptionProcessBuilderReferenceQueueRunnableRuntimeStringStringBufferStringBuilderSystemmathMockitonetAuthenticatorConnectExceptionCookieManagerCookieStoreDatagramPacketHttpCookieInetAddressJarURLConnectionMalformedURLExceptionMulticastSocketNetworkInterfaceServerSocketSocketSocketExceptionSocketTimeoutExceptionUnknownHostExceptionURISyntaxExceptionURLURLClassLoaderURLConnectionURLDecoderURLEncodernioBuff
collectionRelated ConceptsVersion HistorySpringSpring AOPSpring CoreSpring MVCSpring SecurityFrameworksRESTEasyJerseyDropwizardHibernateMavenLog4jLog4j 2JUnitTestNGJPAMore TopicsBest PracticesRegular ExpressionsDesign PatternsPuzzlesAlgorithmsJavaScript/jQueryXMLJDBCHome > Spring > Spring Core > Spring 3 @ExceptionHandler Annotation ExampleSpring 3 @ExceptionHandler Annotation ExampleDecember 18, 2012 by Lokesh Gupta Exception handling is very essential feature of any java program. Every good open source framework allows to write the exception handlers in such a way that you can separate then from your application code. Well, Spring 3 also allows you to do so using annotation @ExceptionHandler. Lets see how all this works.For demonstration, I am adding exception handler in already build code for this article [related to implementing interceptors in spring 3]. So in case any query to project files, please refer to linked post.Download source code for this article Adding exception handlerFor this all you need is to define a method in your controller class and use the annotation @ExceptionHandler on it. Spring's configuration will detect this annotation and register the method as exception handler for given exception and all of its subclasses. There are as such no other guidelines only related to method request and response parameters.@ExceptionHandler(NullPointerException.class) public ModelAndView handleException(NullPointerException ex) { //Do something additional if required ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("error"); modelAndView.addObject("message", ex.getMessage()); return modelAndView; }Now every time, controller encounter above exception in request processing for any web request, control will automatically come to this handler method.For example, below URL is intentionally returning NullPointerException.@RequestMapping(value="/demo/not-exist", method = RequestMethod.GET, headers="Accept=*/*") public @ResponseBody ModelAndView oneFaultyMethod() { if(true) { throw new NullPointerException("This error message if for demo only."); } //Dead code //Read more: http://howtodoinjava.com/puzzles/dead-code-and-unreachable-code-in-java-puzzle/ return null; }If we deploy above application and hit the URL [http ://localhost:8080/firstSpringApplication/users/demo/not-exist] in browser, it will show the error page as configured