Hello, in this chapter we add global exception handling. If you have any questions, please contact me at [email protected]. Ask for directions of various gods, thank you

One: Why do WE need to define global exceptions

Application in the Internet age, we have developed mostly in the form of face to face with the user, the application of any a little carelessness could lead to the loss of users, and anomalies often program is inevitable, so we need to capture of anomaly, and then give the corresponding processing, to reduce the influence of abnormal process for the user experience

Two: Add a service exception

Create ServiceException under the RET folder described earlier

package com.example.demo.core.ret; import java.io.Serializable; /** * @Description: * @author * @date 2018/4/20 14:30 * */ Public Class ServiceException extends RuntimeException implements Serializable{ private static final long serialVersionUID = 1213855733833039552L; publicServiceException() { } public ServiceException(String message) { super(message); } public ServiceException(String message, Throwable cause) { super(message, cause); }}Copy the code

Three: Add exception handling configuration

Open the WebConfigurer created in the previous article and add the following methods

@Override public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) { exceptionResolvers.add(getHandlerExceptionResolver()); } /** * create exception handler * @return
 */
private HandlerExceptionResolver getHandlerExceptionResolver(){
    HandlerExceptionResolver handlerExceptionResolver = new HandlerExceptionResolver(){
        @Override
        public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
                                             Object handler, Exception e) {
            RetResult<Object> result = getResuleByHeandleException(request, handler, e);
            responseResult(response, result);
            returnnew ModelAndView(); }};returnhandlerExceptionResolver; } /** * Return data based on the exception type * @param request * @param handler * @param e * @return
 */
private RetResult<Object> getResuleByHeandleException(HttpServletRequest request, Object handler, Exception e){
    RetResult<Object> result = new RetResult<>();
    if (e instanceof ServiceException) {
        result.setCode(RetCode.FAIL).setMsg(e.getMessage()).setData(null);
        return result;
    }
    if (e instanceof NoHandlerFoundException) {
        result.setCode(RetCode.NOT_FOUND).setMsg("Interface [" + request.getRequestURI() + "] Does not exist");
        return result;
    }
    result.setCode(RetCode.INTERNAL_SERVER_ERROR).setMsg("Interface [" + request.getRequestURI() + "] Internal error, please contact administrator");
    String message;
    if (handler instanceof HandlerMethod) {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        message = String.format("Interface [%s] exception, method: %s.%s, exception Summary: %s", request.getRequestURI(),
                handlerMethod.getBean().getClass().getName(), handlerMethod.getMethod() .getName(), e.getMessage());
    } else {
        message = e.getMessage();
    }
    LOGGER.error(message, e);
    returnresult; } /** * @Title: responseResult * @Description: * @param response * @param result * @reutrn void */ private void responseResult(HttpServletResponse response, RetResult<Object> result) { response.setCharacterEncoding("UTF-8");
    response.setHeader("Content-type"."application/json; charset=UTF-8"); response.setStatus(200); try { response.getWriter().write(JSON.toJSONString(result,SerializerFeature.WriteMapNullValue)); } catch (IOException ex) { LOGGER.error(ex.getMessage()); }}Copy the code

Four: Add a configuration file

In Spring Boot, when a user accesses a link that does not exist, Spring redirects the page to **/error** by default without throwing an exception.

In this case, we tell Spring Boot to throw an exception when a 404 error occurs.

Add two configurations to application.properties:

spring.mvc.throw-exception-if-no-handler-found=true 

spring.resources.add-mappings=false 

In the above configuration, the first spring.mvc. Throw-exception-if-no-handler-found tells SpringBoot to throw an exception when a 404 error occurs. The second spring.resources.add-Mappings tells SpringBoot not to create mappings for resource files in our project.

Five: Create test interfaces

package com.example.demo.service.impl; import com.example.demo.core.ret.ServiceException; import com.example.demo.dao.UserInfoMapper; import com.example.demo.model.UserInfo; import com.example.demo.service.UserInfoService; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; /** * @author * @description: * @time 2018/4/18 11:56 */ @Service public class UserInfoServiceImpl implements UserInfoService{ @Resource private UserInfoMapper userInfoMapper; @Override public UserInfo selectById(Integer id){ UserInfo userInfo = userInfoMapper.selectById(id);if(userInfo == null){
            throw new ServiceException("No user at present");
        }
        returnuserInfo; }}Copy the code

UserInfoController.java

package com.example.demo.controller; import com.example.demo.core.ret.RetResponse; import com.example.demo.core.ret.RetResult; import com.example.demo.core.ret.ServiceException; import com.example.demo.model.UserInfo; import com.example.demo.service.UserInfoService; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import java.util.List; /** * @author * @description: * @time 2018/4/18 11:39 */ @restController @requestMapping ("userInfo")
public class UserInfoController {

    @Resource
    private UserInfoService userInfoService;

    @PostMapping("/hello")
    public String hello() {return "hello SpringBoot";
    }

    @PostMapping("/selectById")
    public RetResult<UserInfo> selectById(Integer id){
        UserInfo userInfo = userInfoService.selectById(id);
        return RetResponse.makeOKRsp(userInfo);
    }

    @PostMapping("/testException")
    public RetResult<UserInfo> testException(Integer id){
        List a = null;
        a.size();
        UserInfo userInfo = userInfoService.selectById(id);
        returnRetResponse.makeOKRsp(userInfo); }}Copy the code

Six: Interface test

Access 192.168.1.104, : 8080 / the userInfo/selectById parameter id: 3

{
    "code": 400,
    "data": null,
    "msg": "No user at present"
}Copy the code

Visit 192.168.1.104, : 8080 / the userInfo testException

{
    "code": 500,
    "data": null,
    "msg": "Interface [/userInfo/testException] internal error, please contact administrator"
}Copy the code

The project address

Code cloud address: gitee.com/beany/mySpr…

GitHub address: github.com/MyBeany/myS…

Writing articles is not easy, if it is helpful to you, please help click star

At the end

Springboot to add global exception handling has been completed, subsequent functions will be updated, if you have any questions, please contact me at [email protected]. Ask for directions from various gods, thank you.