Spring Boot: abnormal unified treatment

Abnormal unified treatment: When setting up a project with springboot, return json data, for example, requires an interface to query the user id of personal information 10. If the query is user id 20, and this user does not exist, we need to return to a friendly deal with information. Then you can write a custom exception, not the query in the results when this exception is thrown, and add the reasons of the information generated in the exception.

Create a project directory structure is as follows:

First look at the code controller layer, only a method, according to the user basic information returned id.

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/user")
    public ResponseEntity getUser(@Param("id")Integer id) throws Exception {
        String result = userService.getUser(id);
        return ResponseEntity.ok(new ResultData<String>(result));
    }
}
View Code

Which calls the service layer method. View Code service layer.

@Service
public class UserService {

    public String getUser(Integer id) {
        User String = null ;
         // simulation database query 
        IF (ID == 10 ) {
            user = "name: tom; age: 12";
        }
        // determine whether or not the results of a query to query an exception is thrown into the 
        IF (the User == null ) {
             the throw  new new MyException ( "505", "CAN not the Find the Record" );
        }
        // return the result 
        return the User;
    }
}

dao layer service call data from the database search, simplified here a little logic, and did not check the data from the database.

Here we throw a custom exception, since abnormal MyException view the contents of the definition:

public class MyException extends RuntimeException{

    private String code;
    private String msg;

    public MyException(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }
}

RuntimeException inherited and added two property values.

Run the project, and then view the information for the user id 20, apparently not, at this time the project returned data is as follows:

{
"timestamp": "2019-11-02T09:13:56.919+0000",
"status": 500,
"error": "Internal Server Error",
"message": "No message available",
"path": "/user"
}

Such data is returned definitely a problem, such a problem is because of our custom exception MyException not handled springmvc built interceptor, you need to customize the look of MyException processing logic.

Add a MyControllerAdvice class, plus @ControllerAdvice notes, its core content is as follows:

@ResponseBody
@ControllerAdvice
public class MyControllerAdvice {

    @ExceptionHandler(Exception.class)
    public Map<String, Object> errorHandle(Exception e){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", -1);
        map.put("msg", e.getMessage());
        return map;
    }

    @ExceptionHandler(value = MyException.class)
    public Map<String,Object> errorHandle(MyException e){
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("code",e.getCode());
        map.put("msg",e.getMsg());
        return map;
    }
}

This class has two methods, a first method is a process commonly Exception exception, this method may be without. The second way is to handle exceptions in our custom. Access to information stored in the map and abnormal returns.

 

Guess you like

Origin www.cnblogs.com/colin220/p/11755304.html