springboot custom exceptions, and custom exception interface

Not much to say nonsense, straight into the main course! !

step:

Setting up an SpringBoot development environment, a little (there can not be a private letter I).

2. Writing a custom exception, custom exception needs to inherit RuntimeException. Write a constructor, and call the parent class save exception information.

public class MyException extends RuntimeException {
    public MyException(String massage) {
        super(massage);
    }
}

3. Write a controller for an exception is thrown. When the request parameter param = aa an exception is thrown, otherwise it does not throw an exception.

@Controller
public class MyController {
    @ResponseBody
    @RequestMapping("/exception")
    public String ee(String param){
       if(param.equals("aa")){
           throw new MyException("抛出自定义异常");
       }
       return "没有抛出异常";
    }
}

When the controller to throw custom exception, this is the status code 500 server error occurs. springboot comes exception interface is not very friendly, we can customize the interface for displaying an exception exception information, see the next step.

4. Custom custom exception handler interface. springboot automatically configures the view resolvers, we can write a 500.html on the classpath: Under tempaltes / error directory.

500.html code is as follows (with the thymeleaf rendering):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
status: [[${status}]] <br>
timestamp: [[${timestamp}]] <br>
message: [[${message}]] <br>
exception: [[${exception}]] <br>
</body>
</html>

Code had been prepared to look at the effect it!
When we visit http: // localhost / exception param = aa throws an exception when results are as follows:?

Visit http:? // localhost / exception param = bb, no exception is thrown, as follows:


** TELL: In the user management system, we can customize the user does not exist exception class when a query a user does not exist, so the controller does not throw user exceptions exist, and jump to a prompt and friendly interface.
Rush tickets system, when the user purchases the tickets have been sold out, we can throw a custom ticket has been no exception, and jump to a prompt and friendly interface. **

Guess you like

Origin www.cnblogs.com/shun-w/p/11589622.html