Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Spring MVC Exception Handling     - Ubuntu How to mount iso file (Linux)

- Java object serialization and deserialization (Programming)

- Keepalived + Nginx Installation and Configuration (Server)

- IPTABLES configuration steps under Linux (Linux)

- Use GLOBK batch command network adjustment (Linux)

- Apache Mina framework Practice (Programming)

- Oracle data files deleted recover after physical (Database)

- Some safety precautions of Linux servers (Linux)

- CentOS 6.4 Python 2.6 upgrade to 2.7 (Linux)

- Linux system Iptables Firewall User Manual (Linux)

- ThinkPad X220 Ubuntu 14.10 installed on fingerprint recognition (Linux)

- OpenWrt modify flash size (Linux)

- Learn about EditText little depth (Programming)

- Linux kernel netpoll framework netconsole (Linux)

- How to Install Linux kernel 4.0 on Ubuntu / CentOS (Linux)

- bash login and welcome message: / etc / issue, / etc / motd (Linux)

- JavaScript Advanced Programming notes event capture and event bubbling (Programming)

- Oracle inline view updates problems encountered (Database)

- JDK tools jstat (Linux)

- LNMP summary of the issues common 502 Bad Gateway (Server)

 
         
  Spring MVC Exception Handling
     
  Add Date : 2018-11-21      
         
         
         
  Using HTTP Status Codes

Use ResponseStatus comment on our custom exception. When our Controller exception is thrown and not handled, he will return HTTP STATUS value specified HTTP RESPONSE, such as:

    @ResponseStatus (Value = HttpStatus.NOT_FOUND, reason = "No such Order") // 404
    public class OrderNotFoundException extends RuntimeException {
        // ...
    }
Our Controller is:

 @RequestMapping (Value = "/ orders / {id}", method = GET)
    public String showOrder (@PathVariable ( "id") long id, Model model) {
        Order order = orderRepository.findOrderById (id);
        if (order == null) throw new OrderNotFoundException (id);
        model.addAttribute (order);
        return "orderDetail";
    }
This time will return to 404 to 404 pages instead of error pages

Controller Based Exception Handling

In one Controller,

, Note that this is only valid for a single Controller. You can do this:

After an exception occurs, change Response status, in general, the occurrence of abnormal returns HTTP STATUS 500. We can become the other.
Go error page after an error occurs
You can define different for different exception handling (such as different error page different Response status)
for example

@Controller
public class ExceptionHandlingController {

  // We marked @RequestMapping methods
  ...
  
  // Method to handle exceptions.
  
  // Our defined exceptions into specific Http status code
  @ResponseStatus (Value = HttpStatus.CONFLICT, reason = "Data integrity violation") // 409
  @ExceptionHandler (DataIntegrityViolationException.class)
  public void conflict () {
    // Nothing to do
  }
  

  After // capture SQLException, DataAccessException abnormal, go to a specific page.
  @ExceptionHandler ({SQLException.class, DataAccessException.class})
  public String databaseError () {
    // Only goes to the error page, we do not get this value Exception on the page, to get value, we can get through the following method
    return "databaseError";
  }

  // By ModelAndView return to the page, and the page to pass the appropriate values
  @ExceptionHandler (Exception.class)
  public ModelAndView handleError (HttpServletRequest req, Exception exception) {
    logger.error ( "Request:" + req.getRequestURL () + "raised" + exception);

    ModelAndView mav = new ModelAndView ();
    mav.addObject ( "exception", exception);
    mav.addObject ( "url", req.getRequestURL ());
    mav.setViewName ( "error");
    return mav;
  }
}
Global Exception Handling

Use @ControllerAdvice annotation on the class, so that we can handle the entire program thrown.

.
Example:

class GlobalControllerExceptionHandler {
    @ResponseStatus (HttpStatus.CONFLICT) // 409
    @ExceptionHandler (DataIntegrityViolationException.class)
    public void handleConflict () {
        // Nothing to do
    }
    
   // Go to a specific page. . . . .
}
If we want all of the exception handler can do:


@ControllerAdvice
class GlobalDefaultExceptionHandler {
    public static final String DEFAULT_ERROR_VIEW = "error";

    @ExceptionHandler (Value = Exception.class)
    public ModelAndView defaultErrorHandler (HttpServletRequest req, Exception e) throws Exception {
        // If the exception is annotated with @ResponseStatus rethrow it and let
        // The framework handle it - like the OrderNotFoundException example
        // At the start of this post.
        // AnnotationUtils is a Spring Framework utility class.
        if (AnnotationUtils.findAnnotation (e.getClass (), ResponseStatus.class)! = null) {
            throw e;
        }
        // Otherwise setup and send the user to a default error-view.
        ModelAndView mav = new ModelAndView ();
        mav.addObject ( "exception", e);
        mav.addObject ( "url", req.getRequestURL ());
        mav.setViewName (DEFAULT_ERROR_VIEW);
        return mav;
    }
}
Going Deeper

HandlerExceptionResolver implement interfaces, SpringMvc can use exception to handle him thrown Controller

public interface HandlerExceptionResolver {
    ModelAndView resolveException (HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception ex);
}
SpringMvc use three default HandlerExceptionResolver to handle our exception

ExceptionHandlerExceptionResolver :.
ResponseStatusExceptionResolver:
DefaultHandlerExceptionResolver: some standard Spring-defined exceptions, be converted to HTTP STATUS CODE.
Spring built SimpleMappingExceptionResolver realized HandlerExceptionResolver interfaces, but also we often use, XML configuration is as follows:

< Bean id = "simpleMappingExceptionResolver"
          class = "org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        < Property name = "exceptionMappings">
            < Map>
                < -! Key for the exception type, value is to go to page ->
                < Entry key = "DatabaseException" value = "databaseError" />
                < Entry key = "InvalidCreditCardException" value = "creditCardError" />
            < / Map>
        < / Property>
        < ! - The default exception page ->
        < Property name = "defaultErrorView" value = "error" />
        < ! - Page we can get through ex exception information ->
        < Property name = "exceptionAttribute" value = "ex" />
        
        < -! Name of logger to use to log exceptions Unset by default, so logging disabled -.>
         < -! Log exception information, the default is not set - do not log exception information ->
        < Property name = "warnLogCategory" value = "example.MvcLogger" />
    < / Bean>
     
         
         
         
  More:      
 
- Management and application Oracle external table (Database)
- CentOS7 installation GAMIT and GMT (Linux)
- Linux network monitoring tools ntopng installation (Linux)
- xCAT line installation on CentOS 6.X (Linux)
- Debian installation (Linux)
- Linux 101 hack book reading notes (Linux)
- Apache Mina framework Practice (Programming)
- How to restart after a crash Cinnamon (Linux)
- How to Install Suricata IDS on a Linux system (Server)
- Realization of Linux operating system illegal IP censorship (Linux)
- Ceph Source Analysis: Network Module (Server)
- php How to prevent being injected (Linux)
- Repair after installing Ubuntu no boot device error (Linux)
- ORA-00911 invalid character error Solution (Database)
- In-depth understanding of PHP ini configuration (Server)
- HAproxy let IP recording back-end RS (Server)
- How to Install Apache on Linux servers (Server)
- Linux and Windows virtual machine shared folders ---- Linux install VMware tools (Linux)
- Linux5.8 installed phpMyAdmin was unable to issue related php-mcrypt (Database)
- Oracle Data Pump Example (Database)
     
           
     
  CopyRight 2002-2020 newfreesoft.com, All Rights Reserved.