ControllerAdvice的使用

controlleradvice类
1. 使用该注解 , 该注解标识的类会获取并修改controller中爆出的相应异常.

package com.imooc.demo.exception;

import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@ControllerAdvice
public class ControllerExceptionHandler {

    @ExceptionHandler(value = MyException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public Map handlerUserNotExistException(MyException m) {
        Map map = new HashMap<>();
        map.put("id",m.getId());
        map.put("message",m.getMessage());
        return map;
    }
// 该方法无效 , 待修改
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public Map handlerValidExistException(BindingResult result) {
        Map map = new HashMap<>();
        if (result != null) {
            if (result.hasErrors()) {
                List errors = result.getAllErrors();
                for (int i = 0; i < errors.size(); i++) {
                    map.put(Integer.toString(i),errors.get(i).getObjectName());
                }
            }
        } else {
            map.put("field","result is null");
        }
        return map;
    }
}
  1. controller异常类
package com.imooc.demo;

import com.imooc.demo.exception.MyException;
import com.imooc.demo.security.User;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@SpringBootApplication
@RestController
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class,args);
    }

    @PostMapping("")
    public String hello() {

        // return "success";
        throw new MyException("12","haha");
        // return "hello";
    }
}
  1. 自定义异常类
package com.imooc.demo.exception;

public class MyException extends RuntimeException{

    private String id;


    public MyException(String id,String message) {
        super(message);
        this.id = id;
    }
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}
  1. 请求url
http://localhost:8080/
  1. 报错信息
{
"id": "12",
"message": "haha"
}

你可能感兴趣的:(spring)